Debian Codegraph @

rpython/rlib/rfloat.py

raw symbols SCIP
1 """Float constants"""
2
3 import math, struct, errno
4 from math import acosh, asinh, atanh, log1p, expm1
5 import sys
6
7 from rpython.annotator.model import SomeString, SomeChar
8 from rpython.rlib import objectmodel, unroll
9 from rpython.rtyper.extfunc import register_external
10 from rpython.rtyper.tool import rffi_platform
11 from rpython.rtyper.lltypesystem import rffi
12 from rpython.translator.tool.cbuild import ExternalCompilationInfo
13 from rpython.rlib.objectmodel import not_rpython
14
15
16 if sys.platform == 'win32':
17 libraries = []
18 else:
19 libraries = ["m"]
20
21 class CConfig:
22 _compilation_info_ = ExternalCompilationInfo(
23 includes=["float.h", "math.h"], libraries=libraries)
24
25 float_constants = ["DBL_MAX", "DBL_MIN", "DBL_EPSILON"]
26 int_constants = ["DBL_MAX_EXP", "DBL_MAX_10_EXP",
27 "DBL_MIN_EXP", "DBL_MIN_10_EXP",
28 "DBL_DIG", "DBL_MANT_DIG",
29 "FLT_RADIX", "FLT_ROUNDS"]
30 for const in float_constants:
31 setattr(CConfig, const, rffi_platform.DefinedConstantDouble(const))
32 for const in int_constants:
33 setattr(CConfig, const, rffi_platform.DefinedConstantInteger(const))
34 del float_constants, int_constants, const
35
36 nextafter = rffi.llexternal(
37 'nextafter', [rffi.DOUBLE, rffi.DOUBLE], rffi.DOUBLE,
38 compilation_info=CConfig._compilation_info_, sandboxsafe=True)
39
40 # exp2, cbrt math functions needed in 3.11+
41
42 math_exp2 = rffi.llexternal('exp2', [rffi.DOUBLE], rffi.DOUBLE,
43 save_err=rffi.RFFI_FULL_ERRNO_ZERO,
44 compilation_info=CConfig._compilation_info_)
45
46 math_cbrt = rffi.llexternal('cbrt', [rffi.DOUBLE], rffi.DOUBLE,
47 save_err=rffi.RFFI_FULL_ERRNO_ZERO,
48 compilation_info=CConfig._compilation_info_)
49
50 globals().update(rffi_platform.configure(CConfig))
51
52 INVALID_MSG = "could not convert string to float"
53
54 def string_to_float(s):
55 """
56 Conversion of string to float.
57 This version tries to only raise on invalid literals.
58 Overflows should be converted to infinity whenever possible.
59
60 Expects an unwrapped string and return an unwrapped float.
61 """
62 from rpython.rlib.rstring import strip_spaces, ParseStringError
63
64 if not s:
65 raise ParseStringError(INVALID_MSG)
66 def iswhitespace(ch):
67 return (ch == ' ' or ch == '\f' or ch == '\n' or ch == '\r' or
68 ch == '\t' or ch == '\v')
69 if iswhitespace(s[0]) or iswhitespace(s[-1]):
70 s = strip_spaces(s)
71 try:
72 return rstring_to_float(s)
73 except ValueError:
74 low = s.lower()
75 if low == "-inf" or low == "-infinity":
76 return -INFINITY
77 elif low == "inf" or low == "+inf":
78 return INFINITY
79 elif low == "infinity" or low == "+infinity":
80 return INFINITY
81 elif low == "nan" or low == "+nan":
82 return NAN
83 elif low == "-nan":
84 return -NAN
85 raise ParseStringError(INVALID_MSG)
86
87 def rstring_to_float(s):
88 from rpython.rlib.rdtoa import strtod
89 return strtod(s)
90
91 # float -> string
92
93 DTSF_STR_PRECISION = 12
94
95 DTSF_SIGN = 0x1
96 DTSF_ADD_DOT_0 = 0x2
97 DTSF_ALT = 0x4
98 DTSF_CUT_EXP_0 = 0x8
99 DTSF_NO_NEG_0 = 0x10
100
101 DIST_FINITE = 1
102 DIST_NAN = 2
103 DIST_INFINITY = 3
104
105 @objectmodel.enforceargs(float, SomeChar(), int, int)
106 def formatd(x, code, precision, flags=0):
107 from rpython.rlib.rdtoa import dtoa_formatd
108 return dtoa_formatd(x, code, precision, flags)
109
110 def double_to_string(value, tp, precision, flags):
111 if isfinite(value):
112 special = DIST_FINITE
113 elif math.isinf(value):
114 special = DIST_INFINITY
115 else: #isnan(value):
116 special = DIST_NAN
117 result = formatd(value, tp, precision, flags)
118 return result, special
119
120 def round_double(value, ndigits, half_even=False):
121 """Round a float half away from zero.
122
123 Specify half_even=True to round half even instead.
124 The argument 'value' must be a finite number. This
125 function may return an infinite number in case of
126 overflow (only if ndigits is a very negative integer).
127 """
128 if ndigits == 0:
129 # fast path for this common case
130 if half_even:
131 return round_half_even(value)
132 else:
133 return round_away(value)
134
135 if value == 0.0:
136 return 0.0
137
138 # The basic idea is very simple: convert and round the double to
139 # a decimal string using _Py_dg_dtoa, then convert that decimal
140 # string back to a double with _Py_dg_strtod. There's one minor
141 # difficulty: Python 2.x expects round to do
142 # round-half-away-from-zero, while _Py_dg_dtoa does
143 # round-half-to-even. So we need some way to detect and correct
144 # the halfway cases.
145
146 # a halfway value has the form k * 0.5 * 10**-ndigits for some
147 # odd integer k. Or in other words, a rational number x is
148 # exactly halfway between two multiples of 10**-ndigits if its
149 # 2-valuation is exactly -ndigits-1 and its 5-valuation is at
150 # least -ndigits. For ndigits >= 0 the latter condition is
151 # automatically satisfied for a binary float x, since any such
152 # float has nonnegative 5-valuation. For 0 > ndigits >= -22, x
153 # needs to be an integral multiple of 5**-ndigits; we can check
154 # this using fmod. For -22 > ndigits, there are no halfway
155 # cases: 5**23 takes 54 bits to represent exactly, so any odd
156 # multiple of 0.5 * 10**n for n >= 23 takes at least 54 bits of
157 # precision to represent exactly.
158
159 sign = math.copysign(1.0, value)
160 value = abs(value)
161
162 # find 2-valuation value
163 m, expo = math.frexp(value)
164 while m != math.floor(m):
165 m *= 2.0
166 expo -= 1
167
168 # determine whether this is a halfway case.
169 halfway_case = 0
170 if not half_even and expo == -ndigits - 1:
171 if ndigits >= 0:
172 halfway_case = 1
173 elif ndigits >= -22:
174 # 22 is the largest k such that 5**k is exactly
175 # representable as a double
176 five_pow = 1.0
177 for i in range(-ndigits):
178 five_pow *= 5.0
179 if math.fmod(value, five_pow) == 0.0:
180 halfway_case = 1
181
182 # round to a decimal string; use an extra place for halfway case
183 strvalue = formatd(value, 'f', ndigits + halfway_case)
184
185 if not half_even and halfway_case:
186 buf = [c for c in strvalue]
187 if ndigits >= 0:
188 endpos = len(buf) - 1
189 else:
190 endpos = len(buf) + ndigits
191 # Sanity checks: there should be exactly ndigits+1 places
192 # following the decimal point, and the last digit in the
193 # buffer should be a '5'
194 if not objectmodel.we_are_translated():
195 assert buf[endpos] == '5'
196 if '.' in buf:
197 assert endpos == len(buf) - 1
198 assert buf.index('.') == len(buf) - ndigits - 2
199
200 # increment and shift right at the same time
201 i = endpos - 1
202 carry = 1
203 while i >= 0:
204 digit = ord(buf[i])
205 if digit == ord('.'):
206 buf[i+1] = chr(digit)
207 i -= 1
208 digit = ord(buf[i])
209
210 carry += digit - ord('0')
211 buf[i+1] = chr(carry % 10 + ord('0'))
212 carry /= 10
213 i -= 1
214 buf[0] = chr(carry + ord('0'))
215 if ndigits < 0:
216 buf.append('0')
217
218 strvalue = ''.join(buf)
219
220 return sign * rstring_to_float(strvalue)
221
222
223 INFINITY = 1e200 * 1e200
224 NAN = abs(INFINITY / INFINITY) # bah, INF/INF gives us -NAN?
225
226
227 def log2(x):
228 # Uses an algorithm that should:
229 # (a) produce exact results for powers of 2, and
230 # (b) be monotonic, assuming that the system log is monotonic.
231 if not isfinite(x):
232 if math.isnan(x):
233 return x # log2(nan) = nan
234 elif x > 0.0:
235 return x # log2(+inf) = +inf
236 else:
237 # log2(-inf) = nan, invalid-operation
238 raise ValueError("math domain error")
239
240 if x > 0.0:
241 if 0: # HAVE_LOG2
242 return math.log2(x)
243 m, e = math.frexp(x)
244 # We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
245 # x is just greater than 1.0: in that case e is 1, log(m) is negative,
246 # and we get significant cancellation error from the addition of
247 # log(m) / log(2) to e. The slight rewrite of the expression below
248 # avoids this problem.
249 if x >= 1.0:
250 return math.log(2.0 * m) / math.log(2.0) + (e - 1)
251 else:
252 return math.log(m) / math.log(2.0) + e
253 else:
254 raise ValueError("math domain error")
255
256 def round_away(x):
257 # round() from libm, which is not available on all platforms!
258 # This version rounds away from zero.
259 absx = abs(x)
260 r = math.floor(absx + 0.5)
261 if r - absx < 1.0:
262 return math.copysign(r, x)
263 else:
264 # 'absx' is just in the wrong range: its exponent is precisely
265 # the one for which all integers are representable but not any
266 # half-integer. It means that 'absx + 0.5' computes equal to
267 # 'absx + 1.0', which is not equal to 'absx'. So 'r - absx'
268 # computes equal to 1.0. In this situation, we can't return
269 # 'r' because 'absx' was already an integer but 'r' is the next
270 # integer! But just returning the original 'x' is fine.
271 return x
272
273 def round_half_even(x):
274 absx = abs(x)
275 r = math.floor(absx + 0.5)
276 frac = r - absx
277 if frac >= 0.5:
278 # two rare cases: either 'absx' is precisely half-way between
279 # two integers (frac == 0.5); or we're in the same situation as
280 # described in round_away above (frac == 1.0).
281 if frac >= 1.0:
282 return x
283 # absx == n + 0.5 for a non-negative integer 'n'
284 # absx * 0.5 == n//2 + 0.25 or 0.75, which we round to nearest
285 r = math.floor(absx * 0.5 + 0.5) * 2.0
286 return math.copysign(r, x)
287
288 @not_rpython
289 def isfinite(x):
290 return not math.isinf(x) and not math.isnan(x)
291
292 def float_as_rbigint_ratio(value):
293 from rpython.rlib.rbigint import rbigint
294
295 if math.isinf(value):
296 raise OverflowError("cannot pass infinity to as_integer_ratio()")
297 elif math.isnan(value):
298 raise ValueError("cannot pass nan to as_integer_ratio()")
299 float_part, exp_int = math.frexp(value)
300 for i in range(300):
301 if float_part == math.floor(float_part):
302 break
303 float_part *= 2.0
304 exp_int -= 1
305 num = rbigint.fromfloat(float_part)
306 den = rbigint.fromint(1)
307 exp = den.lshift(abs(exp_int))
308 if exp_int > 0:
309 num = num.mul(exp)
310 else:
311 den = exp
312 return num, den
313
314
315
316 # Implementation of the error function, the complimentary error function, the
317 # gamma function, and the natural log of the gamma function. These exist in
318 # libm, but I hear those implementations are horrible.
319
320 ERF_SERIES_CUTOFF = 1.5
321 ERF_SERIES_TERMS = 25
322 ERFC_CONTFRAC_CUTOFF = 30.
323 ERFC_CONTFRAC_TERMS = 50
324 _sqrtpi = 1.772453850905516027298167483341145182798
325
326 def _erf_series(x):
327 x2 = x * x
328 acc = 0.
329 fk = ERF_SERIES_TERMS + .5
330 for i in range(ERF_SERIES_TERMS):
331 acc = 2.0 + x2 * acc / fk
332 fk -= 1.
333 return acc * x * math.exp(-x2) / _sqrtpi
334
335 def _erfc_contfrac(x):
336 if x >= ERFC_CONTFRAC_CUTOFF:
337 return 0.
338 x2 = x * x
339 a = 0.
340 da = .5
341 p = 1.
342 p_last = 0.
343 q = da + x2
344 q_last = 1.
345 for i in range(ERFC_CONTFRAC_TERMS):
346 a += da
347 da += 2.
348 b = da + x2
349 p_last, p = p, b * p - a * p_last
350 q_last, q = q, b * q - a * q_last
351 return p / q * x * math.exp(-x2) / _sqrtpi
352
353 def erf(x):
354 """The error function at x."""
355 if math.isnan(x):
356 return x
357 absx = abs(x)
358 if absx < ERF_SERIES_CUTOFF:
359 return _erf_series(x)
360 else:
361 cf = _erfc_contfrac(absx)
362 return 1. - cf if x > 0. else cf - 1.
363
364 def erfc(x):
365 """The complementary error function at x."""
366 if math.isnan(x):
367 return x
368 absx = abs(x)
369 if absx < ERF_SERIES_CUTOFF:
370 return 1. - _erf_series(x)
371 else:
372 cf = _erfc_contfrac(absx)
373 return cf if x > 0. else 2. - cf
374
375 def _sinpi(x):
376 y = math.fmod(abs(x), 2.)
377 n = int(round_away(2. * y))
378 if n == 0:
379 r = math.sin(math.pi * y)
380 elif n == 1:
381 r = math.cos(math.pi * (y - .5))
382 elif n == 2:
383 r = math.sin(math.pi * (1. - y))
384 elif n == 3:
385 r = -math.cos(math.pi * (y - 1.5))
386 elif n == 4:
387 r = math.sin(math.pi * (y - 2.))
388 else:
389 raise AssertionError("should not reach")
390 return math.copysign(1., x) * r
391
392 _lanczos_g = 6.024680040776729583740234375
393 _lanczos_g_minus_half = 5.524680040776729583740234375
394 _lanczos_num_coeffs = [
395 23531376880.410759688572007674451636754734846804940,
396 42919803642.649098768957899047001988850926355848959,
397 35711959237.355668049440185451547166705960488635843,
398 17921034426.037209699919755754458931112671403265390,
399 6039542586.3520280050642916443072979210699388420708,
400 1439720407.3117216736632230727949123939715485786772,
401 248874557.86205415651146038641322942321632125127801,
402 31426415.585400194380614231628318205362874684987640,
403 2876370.6289353724412254090516208496135991145378768,
404 186056.26539522349504029498971604569928220784236328,
405 8071.6720023658162106380029022722506138218516325024,
406 210.82427775157934587250973392071336271166969580291,
407 2.5066282746310002701649081771338373386264310793408
408 ]
409 _lanczos_den_coeffs = [
410 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
411 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0]
412 LANCZOS_N = len(_lanczos_den_coeffs)
413 _lanczos_n_iter = unroll.unrolling_iterable(range(LANCZOS_N))
414 _lanczos_n_iter_back = unroll.unrolling_iterable(range(LANCZOS_N - 1, -1, -1))
415 _gamma_integrals = [
416 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
417 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
418 1307674368000.0, 20922789888000.0, 355687428096000.0,
419 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
420 51090942171709440000.0, 1124000727777607680000.0]
421
422 def _lanczos_sum(x):
423 num = 0.
424 den = 0.
425 assert x > 0.
426 if x < 5.:
427 for i in _lanczos_n_iter_back:
428 num = num * x + _lanczos_num_coeffs[i]
429 den = den * x + _lanczos_den_coeffs[i]
430 else:
431 for i in _lanczos_n_iter:
432 num = num / x + _lanczos_num_coeffs[i]
433 den = den / x + _lanczos_den_coeffs[i]
434 return num / den
435
436 def gamma(x):
437 """Compute the gamma function for x."""
438 if math.isnan(x) or (math.isinf(x) and x > 0.):
439 return x
440 if math.isinf(x):
441 raise ValueError("math domain error")
442 if x == 0.:
443 raise ValueError("math domain error")
444 if x == math.floor(x):
445 if x < 0.:
446 raise ValueError("math domain error")
447 if x < len(_gamma_integrals):
448 return _gamma_integrals[int(x) - 1]
449 absx = abs(x)
450 if absx < 1e-20:
451 r = 1. / x
452 if math.isinf(r):
453 raise OverflowError("math range error")
454 return r
455 if absx > 200.:
456 if x < 0.:
457 return 0. / -_sinpi(x)
458 else:
459 raise OverflowError("math range error")
460 y = absx + _lanczos_g_minus_half
461 if absx > _lanczos_g_minus_half:
462 q = y - absx
463 z = q - _lanczos_g_minus_half
464 else:
465 q = y - _lanczos_g_minus_half
466 z = q - absx
467 z = z * _lanczos_g / y
468 if x < 0.:
469 r = -math.pi / _sinpi(absx) / absx * math.exp(y) / _lanczos_sum(absx)
470 r -= z * r
471 if absx < 140.:
472 r /= math.pow(y, absx - .5)
473 else:
474 sqrtpow = math.pow(y, absx / 2. - .25)
475 r /= sqrtpow
476 r /= sqrtpow
477 else:
478 r = _lanczos_sum(absx) / math.exp(y)
479 r += z * r
480 if absx < 140.:
481 r *= math.pow(y, absx - .5)
482 else:
483 sqrtpow = math.pow(y, absx / 2. - .25)
484 r *= sqrtpow
485 r *= sqrtpow
486 if math.isinf(r):
487 raise OverflowError("math range error")
488 return r
489
490 def lgamma(x):
491 """Compute the natural logarithm of the gamma function for x."""
492 if math.isnan(x):
493 return x
494 if math.isinf(x):
495 return INFINITY
496 if x == math.floor(x) and x <= 2.:
497 if x <= 0.:
498 raise ValueError("math range error")
499 return 0.
500 absx = abs(x)
501 if absx < 1e-20:
502 return -math.log(absx)
503 if x > 0.:
504 r = (math.log(_lanczos_sum(x)) - _lanczos_g + (x - .5) *
505 (math.log(x + _lanczos_g - .5) - 1))
506 else:
507 r = (math.log(math.pi) - math.log(abs(_sinpi(absx))) - math.log(absx) -
508 (math.log(_lanczos_sum(absx)) - _lanczos_g +
509 (absx - .5) * (math.log(absx + _lanczos_g - .5) - 1)))
510 if math.isinf(r):
511 raise OverflowError("math domain error")
512 return r
513
514
515 def to_ulps(x):
516 """Convert a non-NaN float x to an integer, in such a way that
517 adjacent floats are converted to adjacent integers. Then
518 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
519 floats.
520
521 The results from this function will only make sense on platforms
522 where C doubles are represented in IEEE 754 binary64 format.
523
524 """
525 n = struct.unpack('<q', struct.pack('<d', x))[0]
526 if n < 0:
527 n = ~(n+2**63)
528 return n
529
530 def ulps_check(expected, got, ulps=20):
531 """Given non-NaN floats `expected` and `got`,
532 check that they're equal to within the given number of ulps.
533
534 Returns None on success and an error message on failure."""
535
536 ulps_error = to_ulps(got) - to_ulps(expected)
537 if abs(ulps_error) <= ulps:
538 return None
539 return "error = {} ulps; permitted error = {} ulps".format(ulps_error,
540 ulps)
541
542 def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
543 """Determine whether non-NaN floats a and b are equal to within a
544 (small) rounding error. The default values for rel_err and
545 abs_err are chosen to be suitable for platforms where a float is
546 represented by an IEEE 754 double. They allow an error of between
547 9 and 19 ulps."""
548
549 # need to special case infinities, since inf - inf gives nan
550 if math.isinf(expected) and got == expected:
551 return None
552
553 error = got - expected
554
555 permitted_error = max(abs_err, rel_err * abs(expected))
556 if abs(error) < permitted_error:
557 return None
558 return "error = {}; permitted error = {}".format(error,
559 permitted_error)
560 # ____________________________________________________________
561 #
562 # Error handling functions, mainly for ll_math
563
564 ERANGE = errno.ERANGE
565 EDOM = errno.EDOM
566
567 def _likely_raise(errno, x):
568 """Call this with errno != 0. It usually raises the proper RPython
569 exception, but may also just ignore it and return in case of underflow.
570 """
571 from rpython.rtyper.lltypesystem.module.ll_math import math_fabs
572 assert errno
573 if errno == ERANGE:
574 # We consider underflow to not be an error, like CPython.
575 # On some platforms (Ubuntu/ia64) it seems that errno can be
576 # set to ERANGE for subnormal results that do *not* underflow
577 # to zero. So to be safe, we'll ignore ERANGE whenever the
578 # function result is less than one in absolute value.
579 if math_fabs(x) < 1.0:
580 return
581 raise OverflowError("math range error")
582 else:
583 raise ValueError("math domain error")
584
585 @objectmodel.specialize.arg(2)
586 def _error_check_errno_unary_math(x, r, can_overflow):
587 # Error checking fun. Copied from CPython 2.6
588 from rpython.rlib import rposix
589 errno = rposix.get_saved_errno()
590 if not isfinite(r):
591 if math.isnan(r):
592 if math.isnan(x):
593 errno = 0
594 else:
595 errno = EDOM
596 else: # isinf(r)
597 if not isfinite(x):
598 errno = 0
599 elif can_overflow:
600 errno = ERANGE
601 else:
602 errno = EDOM
603 if errno:
604 _likely_raise(errno, r)
605
606 # ____________________________________________________________
607 # some math functions needed in 3.11+
608
609
610 def exp2(x):
611 "Return 2 raised to the power of x."
612 r = math_exp2(x)
613 _error_check_errno_unary_math(x, r, can_overflow=True)
614 return r
615
616 def cbrt(x):
617 "Return cube root of x."
618 r = math_cbrt(x)
619 _error_check_errno_unary_math(x, r, can_overflow=True)
620 return r