PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rlib/rfloat.py

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