Debian Codegraph @

pypy/objspace/std/floatobject.py

raw symbols SCIP
1 import math
2 import operator
3 import sys
4
5 from rpython.rlib import rarithmetic, rfloat, jit
6 from rpython.rlib.rarithmetic import LONG_BIT, intmask, ovfcheck_float_to_int
7 from rpython.rlib.rarithmetic import int_between
8 from rpython.rlib.rbigint import rbigint
9 from rpython.rlib.rfloat import (
10 DTSF_ADD_DOT_0, INFINITY, NAN,
11 float_as_rbigint_ratio, formatd, isfinite)
12 from rpython.rlib.rstring import ParseStringError
13 from rpython.rlib.unroll import unrolling_iterable
14 from rpython.rtyper.lltypesystem.module.ll_math import math_fmod
15 from rpython.tool.sourcetools import func_with_new_name
16
17 from pypy.interpreter.baseobjspace import W_Root
18 from pypy.interpreter.error import OperationError, oefmt
19 from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
20 from pypy.interpreter.typedef import GetSetProperty, TypeDef, default_identity_hash
21 from pypy.objspace.std import newformat
22 from pypy.objspace.std.intobject import HASH_BITS, HASH_MODULUS, W_IntObject
23 from pypy.objspace.std.longobject import (
24 W_AbstractLongObject, newlong_from_float)
25 from rpython.rlib.rarithmetic import (
26 LONG_BIT, intmask, ovfcheck_float_to_int, r_uint)
27 from pypy.objspace.std.util import wrap_parsestringerror, builtinclass_new_args_check
28
29 HASH_INF = 314159
30 HASH_NAN = 0
31
32 # Here 0.30103 is an upper bound for log10(2)
33 NDIGITS_MAX = int((rfloat.DBL_MANT_DIG - rfloat.DBL_MIN_EXP) * 0.30103)
34 NDIGITS_MIN = -int((rfloat.DBL_MAX_EXP + 1) * 0.30103)
35
36 def float2string(x, code, precision):
37 # we special-case explicitly inf and nan here
38 if isfinite(x):
39 s = formatd(x, code, precision, DTSF_ADD_DOT_0)
40 elif math.isinf(x):
41 if x > 0.0:
42 s = "inf"
43 else:
44 s = "-inf"
45 else: # isnan(x):
46 s = "nan"
47 return s
48
49 def float_repr(x):
50 return float2string(x, 'r', 0)
51
52
53 def detect_floatformat():
54 from rpython.rtyper.lltypesystem import rffi, lltype
55 buf = lltype.malloc(rffi.CCHARP.TO, 8, flavor='raw')
56 rffi.cast(rffi.DOUBLEP, buf)[0] = 9006104071832581.0
57 packed = rffi.charpsize2str(buf, 8)
58 if packed == "\x43\x3f\xff\x01\x02\x03\x04\x05":
59 double_format = 'IEEE, big-endian'
60 elif packed == "\x05\x04\x03\x02\x01\xff\x3f\x43":
61 double_format = 'IEEE, little-endian'
62 else:
63 double_format = 'unknown'
64 lltype.free(buf, flavor='raw')
65 #
66 buf = lltype.malloc(rffi.CCHARP.TO, 4, flavor='raw')
67 rffi.cast(rffi.FLOATP, buf)[0] = rarithmetic.r_singlefloat(16711938.0)
68 packed = rffi.charpsize2str(buf, 4)
69 if packed == "\x4b\x7f\x01\x02":
70 float_format = 'IEEE, big-endian'
71 elif packed == "\x02\x01\x7f\x4b":
72 float_format = 'IEEE, little-endian'
73 else:
74 float_format = 'unknown'
75 lltype.free(buf, flavor='raw')
76
77 return double_format, float_format
78
79 _double_format, _float_format = detect_floatformat()
80
81
82 _alpha = zip("abcdef", range(10, 16)) + zip("ABCDEF", range(10, 16))
83 _hex_to_int = zip("0123456789", range(10)) + _alpha
84 _hex_to_int_iterable = unrolling_iterable(_hex_to_int)
85
86 def _hex_from_char(c):
87 for h, v in _hex_to_int_iterable:
88 if h == c:
89 return v
90 return -1
91
92 def _hex_digit(s, j, co_end, float_digits):
93 if j < float_digits:
94 i = co_end - j
95 else:
96 i = co_end - 1 - j
97 return _hex_from_char(s[i])
98
99 def _char_from_hex(number):
100 return "0123456789abcdef"[number]
101
102
103 def make_compare_func(opname):
104 op = getattr(operator, opname)
105
106 if opname == 'eq' or opname == 'ne':
107 def do_compare_bigint(f1, b2):
108 """f1 is a float. b2 is a bigint."""
109 if not isfinite(f1) or math.floor(f1) != f1:
110 return opname == 'ne'
111 b1 = rbigint.fromfloat(f1)
112 res = b1.eq(b2)
113 if opname == 'ne':
114 res = not res
115 return res
116 else:
117 def do_compare_bigint(f1, b2):
118 """f1 is a float. b2 is a bigint."""
119 if not isfinite(f1):
120 return op(f1, 0.0)
121 if opname == 'gt' or opname == 'le':
122 # 'float > long' <==> 'ceil(float) > long'
123 # 'float <= long' <==> 'ceil(float) <= long'
124 f1 = math.ceil(f1)
125 else:
126 # 'float < long' <==> 'floor(float) < long'
127 # 'float >= long' <==> 'floor(float) >= long'
128 f1 = math.floor(f1)
129 b1 = rbigint.fromfloat(f1)
130 return getattr(b1, opname)(b2)
131
132 def _compare(self, space, w_other):
133 if isinstance(w_other, W_FloatObject):
134 return space.newbool(op(self.floatval, w_other.floatval))
135 if isinstance(w_other, W_IntObject):
136 f1 = self.floatval
137 i2 = space.int_w(w_other)
138 # (double-)floats have always at least 48 bits of precision
139 if LONG_BIT > 32 and not int_between(-1, i2 >> 48, 1):
140 res = do_compare_bigint(f1, rbigint.fromint(i2))
141 else:
142 f2 = float(i2)
143 res = op(f1, f2)
144 return space.newbool(res)
145 if isinstance(w_other, W_AbstractLongObject):
146 return space.newbool(do_compare_bigint(self.floatval,
147 space.bigint_w(w_other)))
148 return space.w_NotImplemented
149 return func_with_new_name(_compare, 'descr_' + opname)
150
151 def newint_from_float(space, floatval):
152 """This is also used from module/math/interp_math.py"""
153 try:
154 value = ovfcheck_float_to_int(floatval)
155 except OverflowError:
156 return newlong_from_float(space, floatval)
157 else:
158 return space.newint(value)
159
160 def float_hash(space, w_float, floatval):
161 if math.isnan(floatval):
162 return default_identity_hash(space, w_float)
163 else:
164 return space.newint(_hash_float(floatval))
165
166 class W_FloatObject(W_Root):
167 """This is a implementation of the app-level 'float' type.
168 The constructor takes an RPython float as an argument."""
169 _immutable_fields_ = ['floatval']
170
171 def __init__(self, floatval):
172 self.floatval = floatval
173
174 def unwrap(self, space):
175 return self.floatval
176
177 def int_w(self, space, allow_conversion=True):
178 self._typed_unwrap_error(space, "integer")
179
180 def bigint_w(self, space, allow_conversion=True):
181 self._typed_unwrap_error(space, "integer")
182
183 def float_w(self, space, allow_conversion=True):
184 return self.floatval
185
186 def _float_w(self, space):
187 return self.floatval
188
189 def int(self, space):
190 # this is a speed-up only, for space.int(w_float).
191 if (type(self) is not W_FloatObject and
192 space.is_overloaded(self, space.w_float, '__int__')):
193 return W_Root.int(self, space)
194 return self.descr_trunc(space)
195
196 def is_w(self, space, w_other):
197 from rpython.rlib.longlong2float import float2longlong
198 if not isinstance(w_other, W_FloatObject):
199 return False
200 if self.user_overridden_class or w_other.user_overridden_class:
201 return self is w_other
202 one = float2longlong(space.float_w(self))
203 two = float2longlong(space.float_w(w_other))
204 return one == two
205
206 def immutable_unique_id(self, space):
207 if self.user_overridden_class:
208 return None
209 from rpython.rlib.longlong2float import float2longlong
210 from pypy.objspace.std.util import IDTAG_FLOAT as tag
211 from pypy.objspace.std.util import IDTAG_SHIFT
212 val = float2longlong(space.float_w(self))
213 b = rbigint.fromrarith_int(val)
214 b = b.lshift(IDTAG_SHIFT).int_or_(tag)
215 return space.newlong_from_rbigint(b)
216
217 def __repr__(self):
218 return "<W_FloatObject(%f)>" % self.floatval
219
220 @staticmethod
221 @unwrap_spec(w_x=WrappedDefault(0.0))
222 def descr__new__(space, w_floattype, w_x, __posonly__, __args__):
223 builtinclass_new_args_check(space, "float", space.w_float, w_floattype, __args__)
224 w_value = w_x # 'x' is the keyword argument name in CPython
225 if space.lookup(w_value, "__float__") is not None:
226 w_obj = space.float(w_value)
227 w_obj_type = space.type(w_obj)
228 if not space.is_w(w_obj_type, space.w_float):
229 space.warn(space.newtext(
230 "%s.__float__ returned non-float (type %s). "
231 "The ability to return an instance of a strict subclass "
232 "of float is deprecated, and may be removed "
233 "in a future version of Python." %
234 (space.type(w_value).name, w_obj_type.name)),
235 space.w_DeprecationWarning)
236 elif space.is_w(w_floattype, space.w_float):
237 return w_obj
238 value = space.float_w(w_obj)
239 elif space.lookup(w_value, "__index__") is not None:
240 w_obj = space.index(w_value)
241 return space.float(w_obj)
242 elif space.isinstance_w(w_value, space.w_unicode):
243 from unicodeobject import unicode_to_decimal_w
244 value = _string_to_float(space, w_value,
245 unicode_to_decimal_w(space, w_value))
246 else:
247 try:
248 value = space.charbuf_w(w_value)
249 except OperationError as e:
250 if e.match(space, space.w_TypeError):
251 raise oefmt(space.w_TypeError,
252 "float() argument must be a string or a "
253 "number, not '%T'", w_value)
254 raise
255 value = _string_to_float(space, w_value, value)
256 w_obj = space.allocate_instance(W_FloatObject, w_floattype)
257 W_FloatObject.__init__(w_obj, value)
258 return w_obj
259
260 @staticmethod
261 @unwrap_spec(kind='text')
262 def descr___getformat__(space, w_cls, kind):
263 if kind == "float":
264 return space.newtext(_float_format)
265 elif kind == "double":
266 return space.newtext(_double_format)
267 raise oefmt(space.w_ValueError, "only float and double are valid")
268
269 @staticmethod
270 @unwrap_spec(s='text')
271 def descr_fromhex(space, w_cls, s):
272 """float.fromhex(string) -> float
273
274 Create a floating-point number from a hexadecimal string.
275 >>> float.fromhex('0x1.ffffp10')
276 2047.984375
277 >>> float.fromhex('-0x1p-1074')
278 -5e-324
279
280 """
281 length = len(s)
282 i = 0
283 value = 0.0
284 while i < length and s[i].isspace():
285 i += 1
286 if i == length:
287 raise oefmt(space.w_ValueError, "invalid hex string")
288 sign = 1
289 if s[i] == "-":
290 sign = -1
291 i += 1
292 elif s[i] == "+":
293 i += 1
294 if length == i:
295 raise oefmt(space.w_ValueError, "invalid hex string")
296 if s[i] == "i" or s[i] == "I":
297 i += 1
298 if length - i >= 2 and s[i:i + 2].lower() == "nf":
299 i += 2
300 value = rfloat.INFINITY
301 if length - i >= 5 and s[i:i + 5].lower() == "inity":
302 i += 5
303 elif s[i] == "n" or s[i] == "N":
304 i += 1
305 if length - i >= 2 and s[i:i + 2].lower() == "an":
306 i += 2
307 value = rfloat.NAN
308 else:
309 if (s[i] == "0" and length - i > 1 and
310 (s[i + 1] == "x" or s[i + 1] == "X")):
311 i += 2
312 co_start = i
313 while i < length and _hex_from_char(s[i]) >= 0:
314 i += 1
315 whole_end = i
316 if i < length and s[i] == ".":
317 i += 1
318 while i < length and _hex_from_char(s[i]) >= 0:
319 i += 1
320 co_end = i - 1
321 else:
322 co_end = i
323 total_digits = co_end - co_start
324 float_digits = co_end - whole_end
325 if not total_digits:
326 raise oefmt(space.w_ValueError, "invalid hex string")
327 const_one = rfloat.DBL_MIN_EXP - rfloat.DBL_MANT_DIG + sys.maxint // 2
328 const_two = sys.maxint // 2 + 1 - rfloat.DBL_MAX_EXP
329 if total_digits > min(const_one, const_two) // 4:
330 raise oefmt(space.w_ValueError, "way too long")
331 if i < length and (s[i] == "p" or s[i] == "P"):
332 i += 1
333 if i == length:
334 raise oefmt(space.w_ValueError, "invalid hex string")
335 exp_sign = 1
336 if s[i] == "-" or s[i] == "+":
337 if s[i] == "-":
338 exp_sign = -1
339 i += 1
340 if i == length:
341 raise oefmt(space.w_ValueError, "invalid hex string")
342 if not s[i].isdigit():
343 raise oefmt(space.w_ValueError, "invalid hex string")
344 exp = ord(s[i]) - ord('0')
345 i += 1
346 while i < length and s[i].isdigit():
347 exp = exp * 10 + (ord(s[i]) - ord('0'))
348 if exp >= (sys.maxint-9) // 10:
349 if exp_sign > 0:
350 exp_sign = 2 # overflow in positive numbers
351 else:
352 exp_sign = -2 # overflow in negative numbers
353 i += 1
354 if exp_sign == -1:
355 exp = -exp
356 elif exp_sign == -2:
357 exp = -sys.maxint / 2
358 elif exp_sign == 2:
359 exp = sys.maxint / 2
360 else:
361 exp = 0
362 while (total_digits and
363 _hex_digit(s, total_digits - 1, co_end, float_digits) == 0):
364 total_digits -= 1
365 if not total_digits or exp <= -sys.maxint / 2:
366 value = 0.0
367 elif exp >= sys.maxint // 2:
368 raise oefmt(space.w_OverflowError, "too large")
369 else:
370 exp -= 4 * float_digits
371 top_exp = exp + 4 * (total_digits - 1)
372 digit = _hex_digit(s, total_digits - 1, co_end, float_digits)
373 while digit:
374 top_exp += 1
375 digit //= 2
376 if top_exp < rfloat.DBL_MIN_EXP - rfloat.DBL_MANT_DIG:
377 value = 0.0
378 elif top_exp > rfloat.DBL_MAX_EXP:
379 raise oefmt(space.w_OverflowError, "too large")
380 else:
381 lsb = max(top_exp, rfloat.DBL_MIN_EXP) - rfloat.DBL_MANT_DIG
382 value = 0
383 if exp >= lsb:
384 for j in range(total_digits - 1, -1, -1):
385 value = 16.0 * value + _hex_digit(s, j, co_end,
386 float_digits)
387 value = math.ldexp(value, exp)
388 else:
389 half_eps = 1 << ((lsb - exp - 1) % 4)
390 key_digit = (lsb - exp - 1) // 4
391 for j in range(total_digits - 1, key_digit, -1):
392 value = 16.0 * value + _hex_digit(s, j, co_end,
393 float_digits)
394 digit = _hex_digit(s, key_digit, co_end, float_digits)
395 value = 16.0 * value + (digit & (16 - 2*half_eps))
396 if digit & half_eps:
397 round_up = False
398 if (digit & (3 * half_eps - 1) or
399 (half_eps == 8 and key_digit + 1 < float_digits and
400 _hex_digit(s, key_digit + 1, co_end, float_digits) & 1)):
401 round_up = True
402 else:
403 for j in range(key_digit - 1, -1, -1):
404 if _hex_digit(s, j, co_end, float_digits):
405 round_up = True
406 break
407 if round_up:
408 value += 2 * half_eps
409 mant_dig = rfloat.DBL_MANT_DIG
410 if (top_exp == rfloat.DBL_MAX_EXP and
411 value == math.ldexp(2 * half_eps, mant_dig)):
412 raise oefmt(space.w_OverflowError, "too large")
413 value = math.ldexp(value, (exp + 4*key_digit))
414 while i < length and s[i].isspace():
415 i += 1
416 if i != length:
417 raise oefmt(space.w_ValueError, "invalid hex string")
418 w_float = space.newfloat(sign * value)
419 return space.call_function(w_cls, w_float)
420
421 def _to_float(self, space, w_obj):
422 if isinstance(w_obj, W_FloatObject):
423 return w_obj
424 if space.isinstance_w(w_obj, space.w_int):
425 return W_FloatObject(space.float_w(w_obj))
426
427 def descr___round__(self, space, w_ndigits=None):
428 return _round_float(space, self, w_ndigits)
429
430 def descr_repr(self, space):
431 res = float_repr(self.floatval)
432 return space.newutf8(res, len(res)) # always ascii
433
434 def descr_hash(self, space):
435 return float_hash(space, self, self.floatval)
436
437 def descr_format(self, space, w_spec):
438 return newformat.run_formatter(space, w_spec, "format_float", self)
439
440 def descr_bool(self, space):
441 return space.newbool(self.floatval != 0.0)
442
443 def descr_float(self, space):
444 if space.is_w(space.type(self), space.w_float):
445 return self
446 a = self.floatval
447 return W_FloatObject(a)
448
449 def descr_trunc(self, space):
450 return newint_from_float(space, self.floatval)
451
452 def descr_floor(self, space):
453 return newint_from_float(space, math.floor(self.floatval))
454
455 def descr_ceil(self, space):
456 return newint_from_float(space, math.ceil(self.floatval))
457
458 def descr_neg(self, space):
459 return W_FloatObject(-self.floatval)
460
461 def descr_pos(self, space):
462 return self.descr_float(space)
463
464 def descr_abs(self, space):
465 return W_FloatObject(abs(self.floatval))
466
467 def descr_getnewargs(self, space):
468 return space.newtuple([self.descr_float(space)])
469
470 descr_eq = make_compare_func('eq')
471 descr_ne = make_compare_func('ne')
472 descr_lt = make_compare_func('lt')
473 descr_le = make_compare_func('le')
474 descr_gt = make_compare_func('gt')
475 descr_ge = make_compare_func('ge')
476
477 def descr_add(self, space, w_rhs):
478 w_rhs = self._to_float(space, w_rhs)
479 if w_rhs is None:
480 return space.w_NotImplemented
481 return W_FloatObject(self.floatval + w_rhs.floatval)
482
483 def descr_radd(self, space, w_lhs):
484 w_lhs = self._to_float(space, w_lhs)
485 if w_lhs is None:
486 return space.w_NotImplemented
487 return W_FloatObject(w_lhs.floatval + self.floatval)
488
489 def descr_sub(self, space, w_rhs):
490 w_rhs = self._to_float(space, w_rhs)
491 if w_rhs is None:
492 return space.w_NotImplemented
493 return W_FloatObject(self.floatval - w_rhs.floatval)
494
495 def descr_rsub(self, space, w_lhs):
496 w_lhs = self._to_float(space, w_lhs)
497 if w_lhs is None:
498 return space.w_NotImplemented
499 return W_FloatObject(w_lhs.floatval - self.floatval)
500
501 def descr_mul(self, space, w_rhs):
502 w_rhs = self._to_float(space, w_rhs)
503 if w_rhs is None:
504 return space.w_NotImplemented
505 return W_FloatObject(self.floatval * w_rhs.floatval)
506
507 def descr_rmul(self, space, w_lhs):
508 w_lhs = self._to_float(space, w_lhs)
509 if w_lhs is None:
510 return space.w_NotImplemented
511 return W_FloatObject(w_lhs.floatval * self.floatval)
512
513 def descr_div(self, space, w_rhs):
514 w_rhs = self._to_float(space, w_rhs)
515 if w_rhs is None:
516 return space.w_NotImplemented
517 rhs = w_rhs.floatval
518 if rhs == 0.0:
519 raise oefmt(space.w_ZeroDivisionError, "float division by zero")
520 return W_FloatObject(self.floatval / rhs)
521
522 def descr_rdiv(self, space, w_lhs):
523 w_lhs = self._to_float(space, w_lhs)
524 if w_lhs is None:
525 return space.w_NotImplemented
526 selfval = self.floatval
527 if selfval == 0.0:
528 raise oefmt(space.w_ZeroDivisionError, "float division by zero")
529 return W_FloatObject(w_lhs.floatval / selfval)
530
531 def descr_floordiv(self, space, w_rhs):
532 w_rhs = self._to_float(space, w_rhs)
533 if w_rhs is None:
534 return space.w_NotImplemented
535 return _divmod_w(space, self, w_rhs)[0]
536
537 def descr_rfloordiv(self, space, w_lhs):
538 w_lhs = self._to_float(space, w_lhs)
539 if w_lhs is None:
540 return space.w_NotImplemented
541 return _divmod_w(space, w_lhs, self)[0]
542
543 def descr_mod(self, space, w_rhs):
544 w_rhs = self._to_float(space, w_rhs)
545 if w_rhs is None:
546 return space.w_NotImplemented
547 x = self.floatval
548 y = w_rhs.floatval
549 if y == 0.0:
550 raise oefmt(space.w_ZeroDivisionError, "float modulo")
551 mod = math_fmod(x, y)
552 if mod:
553 # ensure the remainder has the same sign as the denominator
554 if (y < 0.0) != (mod < 0.0):
555 mod += y
556 else:
557 # the remainder is zero, and in the presence of signed zeroes
558 # fmod returns different results across platforms; ensure
559 # it has the same sign as the denominator; we'd like to do
560 # "mod = y * 0.0", but that may get optimized away
561 mod = math.copysign(0.0, y)
562
563 return W_FloatObject(mod)
564
565 def descr_rmod(self, space, w_lhs):
566 w_lhs = self._to_float(space, w_lhs)
567 if w_lhs is None:
568 return space.w_NotImplemented
569 return w_lhs.descr_mod(space, self)
570
571 def descr_divmod(self, space, w_rhs):
572 w_rhs = self._to_float(space, w_rhs)
573 if w_rhs is None:
574 return space.w_NotImplemented
575 return space.newtuple(_divmod_w(space, self, w_rhs))
576
577 def descr_rdivmod(self, space, w_lhs):
578 w_lhs = self._to_float(space, w_lhs)
579 if w_lhs is None:
580 return space.w_NotImplemented
581 return space.newtuple(_divmod_w(space, w_lhs, self))
582
583 @unwrap_spec(w_third_arg=WrappedDefault(None))
584 def descr_pow(self, space, w_rhs, w_third_arg):
585 w_rhs = self._to_float(space, w_rhs)
586 if w_rhs is None:
587 return space.w_NotImplemented
588 if not space.is_w(w_third_arg, space.w_None):
589 raise oefmt(space.w_TypeError, "pow() 3rd argument not allowed "
590 "unless all arguments are integers")
591 x = self.floatval
592 y = w_rhs.floatval
593
594 try:
595 result = _pow(space, x, y)
596 except PowDomainError:
597 # Negative numbers raised to fractional powers become complex
598 return space.pow(space.newcomplex(x, 0.0),
599 space.newcomplex(y, 0.0),
600 w_third_arg)
601 return W_FloatObject(result)
602
603 @unwrap_spec(w_third_arg=WrappedDefault(None))
604 def descr_rpow(self, space, w_lhs, w_third_arg):
605 w_lhs = self._to_float(space, w_lhs)
606 if w_lhs is None:
607 return space.w_NotImplemented
608 return w_lhs.descr_pow(space, self, w_third_arg)
609
610 def descr_get_real(self, space):
611 return space.float(self)
612
613 def descr_get_imag(self, space):
614 return space.newfloat(0.0)
615
616 def descr_conjugate(self, space):
617 return space.float(self)
618
619 def descr_is_integer(self, space):
620 v = self.floatval
621 if not rfloat.isfinite(v):
622 return space.w_False
623 return space.newbool(math.floor(v) == v)
624
625 def descr_as_integer_ratio(self, space):
626 """float.as_integer_ratio() -> (int, int)
627
628 Return a pair of integers, whose ratio is exactly equal to the
629 original float and with a positive denominator. Raise
630 OverflowError on infinities and a ValueError on NaNs.
631
632 >>> (10.0).as_integer_ratio()
633 (10, 1)
634 >>> (0.0).as_integer_ratio()
635 (0, 1)
636 >>> (-.25).as_integer_ratio()
637 (-1, 4)
638
639 """
640 value = self.floatval
641 try:
642 num, den = float_as_rbigint_ratio(value)
643 except OverflowError:
644 raise oefmt(space.w_OverflowError,
645 "cannot convert Infinity to integer ratio")
646 except ValueError:
647 raise oefmt(space.w_ValueError,
648 "cannot convert NaN to integer ratio")
649
650 w_num = space.newlong_from_rbigint(num)
651 w_den = space.newlong_from_rbigint(den)
652 # Try to return int
653 return space.newtuple2(space.int(w_num), space.int(w_den))
654
655 def descr_hex(self, space):
656 """float.hex() -> string
657
658 Return a hexadecimal representation of a floating-point
659 number.
660
661 >>> (-0.1).hex()
662 '-0x1.999999999999ap-4'
663 >>> 3.14159.hex()
664 '0x1.921f9f01b866ep+1'
665
666 """
667 TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4
668 value = self.floatval
669 if not isfinite(value):
670 return self.descr_repr(space)
671 if value == 0.0:
672 if math.copysign(1., value) == -1.:
673 return space.newtext("-0x0.0p+0")
674 else:
675 return space.newtext("0x0.0p+0")
676 mant, exp = math.frexp(value)
677 shift = 1 - max(rfloat.DBL_MIN_EXP - exp, 0)
678 mant = math.ldexp(mant, shift)
679 mant = abs(mant)
680 exp -= shift
681 result = ['\0'] * ((TOHEX_NBITS - 1) // 4 + 2)
682 result[0] = _char_from_hex(int(mant))
683 mant -= int(mant)
684 result[1] = "."
685 for i in range((TOHEX_NBITS - 1) // 4):
686 mant *= 16.0
687 result[i + 2] = _char_from_hex(int(mant))
688 mant -= int(mant)
689 if exp < 0:
690 sign = "-"
691 else:
692 sign = "+"
693 exp = abs(exp)
694 s = ''.join(result)
695 if value < 0.0:
696 return space.newtext("-0x%sp%s%d" % (s, sign, exp))
697 else:
698 return space.newtext("0x%sp%s%d" % (s, sign, exp))
699
700
701 W_FloatObject.typedef = TypeDef("float",
702 __doc__ = '''float(x) -> floating point number
703
704 Convert a string or number to a floating point number, if possible.''',
705 __new__ = interp2app(W_FloatObject.descr__new__),
706 __getformat__ = interp2app(W_FloatObject.descr___getformat__, as_classmethod=True),
707 __round__ = interp2app(W_FloatObject.descr___round__),
708 fromhex = interp2app(W_FloatObject.descr_fromhex, as_classmethod=True),
709 __repr__ = interp2app(W_FloatObject.descr_repr),
710 __hash__ = interp2app(W_FloatObject.descr_hash),
711 __format__ = interp2app(W_FloatObject.descr_format),
712 __bool__ = interp2app(W_FloatObject.descr_bool),
713 __int__ = interp2app(W_FloatObject.descr_trunc),
714 __float__ = interp2app(W_FloatObject.descr_float),
715 __trunc__ = interp2app(W_FloatObject.descr_trunc),
716 __floor__ = interp2app(W_FloatObject.descr_floor),
717 __ceil__ = interp2app(W_FloatObject.descr_ceil),
718 __neg__ = interp2app(W_FloatObject.descr_neg),
719 __pos__ = interp2app(W_FloatObject.descr_pos),
720 __abs__ = interp2app(W_FloatObject.descr_abs),
721 __getnewargs__ = interp2app(W_FloatObject.descr_getnewargs),
722
723 __eq__ = interp2app(W_FloatObject.descr_eq),
724 __ne__ = interp2app(W_FloatObject.descr_ne),
725 __lt__ = interp2app(W_FloatObject.descr_lt),
726 __le__ = interp2app(W_FloatObject.descr_le),
727 __gt__ = interp2app(W_FloatObject.descr_gt),
728 __ge__ = interp2app(W_FloatObject.descr_ge),
729
730 __add__ = interp2app(W_FloatObject.descr_add),
731 __radd__ = interp2app(W_FloatObject.descr_radd),
732 __sub__ = interp2app(W_FloatObject.descr_sub),
733 __rsub__ = interp2app(W_FloatObject.descr_rsub),
734 __mul__ = interp2app(W_FloatObject.descr_mul),
735 __rmul__ = interp2app(W_FloatObject.descr_rmul),
736 __truediv__ = interp2app(W_FloatObject.descr_div),
737 __rtruediv__ = interp2app(W_FloatObject.descr_rdiv),
738 __floordiv__ = interp2app(W_FloatObject.descr_floordiv),
739 __rfloordiv__ = interp2app(W_FloatObject.descr_rfloordiv),
740 __mod__ = interp2app(W_FloatObject.descr_mod),
741 __rmod__ = interp2app(W_FloatObject.descr_rmod),
742 __divmod__ = interp2app(W_FloatObject.descr_divmod),
743 __rdivmod__ = interp2app(W_FloatObject.descr_rdivmod),
744 __pow__ = interp2app(W_FloatObject.descr_pow),
745 __rpow__ = interp2app(W_FloatObject.descr_rpow),
746
747 real = GetSetProperty(W_FloatObject.descr_get_real),
748 imag = GetSetProperty(W_FloatObject.descr_get_imag),
749 conjugate = interp2app(W_FloatObject.descr_conjugate),
750 is_integer = interp2app(W_FloatObject.descr_is_integer),
751 as_integer_ratio = interp2app(W_FloatObject.descr_as_integer_ratio),
752 hex = interp2app(W_FloatObject.descr_hex),
753 )
754
755 def _remove_underscores(string):
756 i = 0
757 prev = '?'
758 res = []
759 for i in range(len(string)):
760 c = string[i]
761 if c == '_':
762 # undercores can only come after digits
763 if not ord('0') <= ord(prev) <= ord('9'):
764 raise ValueError
765 else:
766 res.append(c)
767 # undercores can only come before digits
768 if prev == '_' and not ord('0') <= ord(c) <= ord('9'):
769 raise ValueError
770 prev = c
771 if prev == "_": # not allowed at end
772 raise ValueError
773 return "".join(res)
774
775 def _string_to_float(space, w_source, string):
776 try:
777 if "_" in string:
778 string = _remove_underscores(string)
779 except ValueError:
780 pass
781 else:
782 try:
783 return rfloat.string_to_float(string)
784 except ParseStringError as e:
785 pass
786 raise oefmt(space.w_ValueError,
787 "could not convert string to float: %R", w_source)
788
789 @jit.elidable
790 def _hash_float(v):
791 if math.isinf(v):
792 return HASH_INF if v > 0 else -HASH_INF
793 # nan hash is handled elsewhere
794
795 m, e = math.frexp(v)
796
797 sign = 1
798 if m < 0:
799 sign = -1
800 m = -m
801
802 # process 28 bits at a time; this should work well both for binary
803 # and hexadecimal floating point.
804 x = r_uint(0)
805 while m:
806 x = ((x << 28) & HASH_MODULUS) | x >> (HASH_BITS - 28)
807 m *= 268435456.0 # 2**28
808 e -= 28
809 y = r_uint(m) # pull out integer part
810 m -= y
811 x += y
812 if x >= HASH_MODULUS:
813 x -= HASH_MODULUS
814
815 # adjust for the exponent; first reduce it modulo HASH_BITS
816 e = e % HASH_BITS if e >= 0 else HASH_BITS - 1 - ((-1 - e) % HASH_BITS)
817 x = ((x << e) & HASH_MODULUS) | x >> (HASH_BITS - e)
818
819 x = intmask(intmask(x) * sign)
820 x -= (x == -1)
821 return x
822
823
824 def _divmod_w(space, w_float1, w_float2):
825 x = w_float1.floatval
826 y = w_float2.floatval
827 if y == 0.0:
828 raise oefmt(space.w_ZeroDivisionError, "float modulo")
829 mod = math_fmod(x, y)
830 # fmod is typically exact, so vx-mod is *mathematically* an
831 # exact multiple of wx. But this is fp arithmetic, and fp
832 # vx - mod is an approximation; the result is that div may
833 # not be an exact integral value after the division, although
834 # it will always be very close to one.
835 div = (x - mod) / y
836 if (mod):
837 # ensure the remainder has the same sign as the denominator
838 if ((y < 0.0) != (mod < 0.0)):
839 mod += y
840 div -= 1.0
841 else:
842 # the remainder is zero, and in the presence of signed zeroes
843 # fmod returns different results across platforms; ensure
844 # it has the same sign as the denominator; we'd like to do
845 # "mod = wx * 0.0", but that may get optimized away
846 mod *= mod # hide "mod = +0" from optimizer
847 if y < 0.0:
848 mod = -mod
849 # snap quotient to nearest integral value
850 if div:
851 floordiv = math.floor(div)
852 if (div - floordiv > 0.5):
853 floordiv += 1.0
854 else:
855 # div is zero - get the same sign as the true quotient
856 div *= div # hide "div = +0" from optimizers
857 floordiv = div * x / y # zero w/ sign of vx/wx
858
859 return [W_FloatObject(floordiv), W_FloatObject(mod)]
860
861
862 class PowDomainError(ValueError):
863 """Signals a negative number raised to a fractional power"""
864
865 def _pow(space, x, y):
866 # Sort out special cases here instead of relying on pow()
867 if y == 2.0: # special case for performance:
868 return x * x # x * x is always correct
869 if y == 0.0:
870 # x**0 is 1, even 0**0
871 return 1.0
872 if math.isnan(x):
873 # nan**y = nan, unless y == 0
874 return x
875 if math.isnan(y):
876 # x**nan = nan, unless x == 1; x**nan = x
877 if x == 1.0:
878 return 1.0
879 else:
880 return y
881 if math.isinf(y):
882 # x**inf is: 0.0 if abs(x) < 1; 1.0 if abs(x) == 1; inf if
883 # abs(x) > 1 (including case where x infinite)
884 #
885 # x**-inf is: inf if abs(x) < 1; 1.0 if abs(x) == 1; 0.0 if
886 # abs(x) > 1 (including case where v infinite)
887 x = abs(x)
888 if x == 1.0:
889 return 1.0
890 elif (y > 0.0) == (x > 1.0):
891 return INFINITY
892 else:
893 return 0.0
894 if math.isinf(x):
895 # (+-inf)**w is: inf for w positive, 0 for w negative; in oth
896 # cases, we need to add the appropriate sign if w is an odd
897 # integer.
898 y_is_odd = math.fmod(abs(y), 2.0) == 1.0
899 if y > 0.0:
900 if y_is_odd:
901 return x
902 else:
903 return abs(x)
904 else:
905 if y_is_odd:
906 return math.copysign(0.0, x)
907 else:
908 return 0.0
909
910 if x == 0.0:
911 if y < 0.0:
912 raise oefmt(space.w_ZeroDivisionError,
913 "0.0 cannot be raised to a negative power")
914
915 negate_result = False
916 # special case: "(-1.0) ** bignum" should not raise PowDomainError,
917 # unlike "math.pow(-1.0, bignum)". See http://mail.python.org/
918 # - pipermail/python-bugs-list/2003-March/016795.html
919 if x < 0.0:
920 if math.isnan(y):
921 return NAN
922 if math.floor(y) != y:
923 raise PowDomainError
924 # y is an exact integer, albeit perhaps a very large one.
925 # Replace x by its absolute value and remember to negate the
926 # pow result if y is odd.
927 x = -x
928 negate_result = math.fmod(abs(y), 2.0) == 1.0
929
930 if x == 1.0:
931 # (-1) ** large_integer also ends up here
932 if negate_result:
933 return -1.0
934 else:
935 return 1.0
936
937 try:
938 # We delegate to our implementation of math.pow() the error detection.
939 z = math.pow(x, y)
940 except OverflowError:
941 raise oefmt(space.w_OverflowError, "float power")
942 except ValueError:
943 raise oefmt(space.w_ValueError, "float power")
944
945 if negate_result:
946 z = -z
947 return z
948
949
950 def _round_float(space, w_float, w_ndigits=None):
951 # Algorithm copied directly from CPython
952 x = w_float.floatval
953
954 if space.is_none(w_ndigits):
955 # single-argument round: round to nearest integer
956 rounded = rfloat.round_away(x)
957 if math.fabs(x - rounded) == 0.5:
958 # halfway case: round to even
959 rounded = 2.0 * rfloat.round_away(x / 2.0)
960 return newint_from_float(space, rounded)
961
962 # interpret 2nd argument as a Py_ssize_t; clip on overflow
963 ndigits = space.getindex_w(w_ndigits, None)
964
965 # nans and infinities round to themselves
966 if not rfloat.isfinite(x):
967 return space.newfloat(x)
968
969 # Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
970 # always rounds to itself. For ndigits < NDIGITS_MIN, x always
971 # rounds to +-0.0
972 if ndigits > NDIGITS_MAX:
973 return space.newfloat(x)
974 elif ndigits < NDIGITS_MIN:
975 # return 0.0, but with sign of x
976 return space.newfloat(0.0 * x)
977
978 # finite x, and ndigits is not unreasonably large
979 z = rfloat.round_double(x, ndigits, half_even=True)
980 if math.isinf(z):
981 raise oefmt(space.w_OverflowError, "overflow occurred during round")
982 return space.newfloat(z)