libmpf.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. """
  2. Low-level functions for arbitrary-precision floating-point arithmetic.
  3. """
  4. __docformat__ = 'plaintext'
  5. import math
  6. from bisect import bisect
  7. import sys
  8. # Importing random is slow
  9. #from random import getrandbits
  10. getrandbits = None
  11. from .backend import (MPZ, MPZ_TYPE, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE,
  12. BACKEND, STRICT, HASH_MODULUS, HASH_BITS, gmpy, sage, sage_utils)
  13. from .libintmath import (giant_steps,
  14. trailtable, bctable, lshift, rshift, bitcount, trailing,
  15. sqrt_fixed, numeral, isqrt, isqrt_fast, sqrtrem,
  16. bin_to_radix)
  17. # We don't pickle tuples directly for the following reasons:
  18. # 1: pickle uses str() for ints, which is inefficient when they are large
  19. # 2: pickle doesn't work for gmpy mpzs
  20. # Both problems are solved by using hex()
  21. if BACKEND == 'sage':
  22. def to_pickable(x):
  23. sign, man, exp, bc = x
  24. return sign, hex(man), exp, bc
  25. else:
  26. def to_pickable(x):
  27. sign, man, exp, bc = x
  28. return sign, hex(man)[2:], exp, bc
  29. def from_pickable(x):
  30. sign, man, exp, bc = x
  31. return (sign, MPZ(man, 16), exp, bc)
  32. class ComplexResult(ValueError):
  33. pass
  34. try:
  35. intern
  36. except NameError:
  37. intern = lambda x: x
  38. # All supported rounding modes
  39. round_nearest = intern('n')
  40. round_floor = intern('f')
  41. round_ceiling = intern('c')
  42. round_up = intern('u')
  43. round_down = intern('d')
  44. round_fast = round_down
  45. def prec_to_dps(n):
  46. """Return number of accurate decimals that can be represented
  47. with a precision of n bits."""
  48. return max(1, int(round(int(n)/3.3219280948873626)-1))
  49. def dps_to_prec(n):
  50. """Return the number of bits required to represent n decimals
  51. accurately."""
  52. return max(1, int(round((int(n)+1)*3.3219280948873626)))
  53. def repr_dps(n):
  54. """Return the number of decimal digits required to represent
  55. a number with n-bit precision so that it can be uniquely
  56. reconstructed from the representation."""
  57. dps = prec_to_dps(n)
  58. if dps == 15:
  59. return 17
  60. return dps + 3
  61. #----------------------------------------------------------------------------#
  62. # Some commonly needed float values #
  63. #----------------------------------------------------------------------------#
  64. # Regular number format:
  65. # (-1)**sign * mantissa * 2**exponent, plus bitcount of mantissa
  66. fzero = (0, MPZ_ZERO, 0, 0)
  67. fnzero = (1, MPZ_ZERO, 0, 0)
  68. fone = (0, MPZ_ONE, 0, 1)
  69. fnone = (1, MPZ_ONE, 0, 1)
  70. ftwo = (0, MPZ_ONE, 1, 1)
  71. ften = (0, MPZ_FIVE, 1, 3)
  72. fhalf = (0, MPZ_ONE, -1, 1)
  73. # Arbitrary encoding for special numbers: zero mantissa, nonzero exponent
  74. fnan = (0, MPZ_ZERO, -123, -1)
  75. finf = (0, MPZ_ZERO, -456, -2)
  76. fninf = (1, MPZ_ZERO, -789, -3)
  77. # Was 1e1000; this is broken in Python 2.4
  78. math_float_inf = 1e300 * 1e300
  79. #----------------------------------------------------------------------------#
  80. # Rounding #
  81. #----------------------------------------------------------------------------#
  82. # This function can be used to round a mantissa generally. However,
  83. # we will try to do most rounding inline for efficiency.
  84. def round_int(x, n, rnd):
  85. if rnd == round_nearest:
  86. if x >= 0:
  87. t = x >> (n-1)
  88. if t & 1 and ((t & 2) or (x & h_mask[n<300][n])):
  89. return (t>>1)+1
  90. else:
  91. return t>>1
  92. else:
  93. return -round_int(-x, n, rnd)
  94. if rnd == round_floor:
  95. return x >> n
  96. if rnd == round_ceiling:
  97. return -((-x) >> n)
  98. if rnd == round_down:
  99. if x >= 0:
  100. return x >> n
  101. return -((-x) >> n)
  102. if rnd == round_up:
  103. if x >= 0:
  104. return -((-x) >> n)
  105. return x >> n
  106. # These masks are used to pick out segments of numbers to determine
  107. # which direction to round when rounding to nearest.
  108. class h_mask_big:
  109. def __getitem__(self, n):
  110. return (MPZ_ONE<<(n-1))-1
  111. h_mask_small = [0]+[((MPZ_ONE<<(_-1))-1) for _ in range(1, 300)]
  112. h_mask = [h_mask_big(), h_mask_small]
  113. # The >> operator rounds to floor. shifts_down[rnd][sign]
  114. # tells whether this is the right direction to use, or if the
  115. # number should be negated before shifting
  116. shifts_down = {round_floor:(1,0), round_ceiling:(0,1),
  117. round_down:(1,1), round_up:(0,0)}
  118. #----------------------------------------------------------------------------#
  119. # Normalization of raw mpfs #
  120. #----------------------------------------------------------------------------#
  121. # This function is called almost every time an mpf is created.
  122. # It has been optimized accordingly.
  123. def _normalize(sign, man, exp, bc, prec, rnd):
  124. """
  125. Create a raw mpf tuple with value (-1)**sign * man * 2**exp and
  126. normalized mantissa. The mantissa is rounded in the specified
  127. direction if its size exceeds the precision. Trailing zero bits
  128. are also stripped from the mantissa to ensure that the
  129. representation is canonical.
  130. Conditions on the input:
  131. * The input must represent a regular (finite) number
  132. * The sign bit must be 0 or 1
  133. * The mantissa must be positive
  134. * The exponent must be an integer
  135. * The bitcount must be exact
  136. If these conditions are not met, use from_man_exp, mpf_pos, or any
  137. of the conversion functions to create normalized raw mpf tuples.
  138. """
  139. if not man:
  140. return fzero
  141. # Cut mantissa down to size if larger than target precision
  142. n = bc - prec
  143. if n > 0:
  144. if rnd == round_nearest:
  145. t = man >> (n-1)
  146. if t & 1 and ((t & 2) or (man & h_mask[n<300][n])):
  147. man = (t>>1)+1
  148. else:
  149. man = t>>1
  150. elif shifts_down[rnd][sign]:
  151. man >>= n
  152. else:
  153. man = -((-man)>>n)
  154. exp += n
  155. bc = prec
  156. # Strip trailing bits
  157. if not man & 1:
  158. t = trailtable[int(man & 255)]
  159. if not t:
  160. while not man & 255:
  161. man >>= 8
  162. exp += 8
  163. bc -= 8
  164. t = trailtable[int(man & 255)]
  165. man >>= t
  166. exp += t
  167. bc -= t
  168. # Bit count can be wrong if the input mantissa was 1 less than
  169. # a power of 2 and got rounded up, thereby adding an extra bit.
  170. # With trailing bits removed, all powers of two have mantissa 1,
  171. # so this is easy to check for.
  172. if man == 1:
  173. bc = 1
  174. return sign, man, exp, bc
  175. def _normalize1(sign, man, exp, bc, prec, rnd):
  176. """same as normalize, but with the added condition that
  177. man is odd or zero
  178. """
  179. if not man:
  180. return fzero
  181. if bc <= prec:
  182. return sign, man, exp, bc
  183. n = bc - prec
  184. if rnd == round_nearest:
  185. t = man >> (n-1)
  186. if t & 1 and ((t & 2) or (man & h_mask[n<300][n])):
  187. man = (t>>1)+1
  188. else:
  189. man = t>>1
  190. elif shifts_down[rnd][sign]:
  191. man >>= n
  192. else:
  193. man = -((-man)>>n)
  194. exp += n
  195. bc = prec
  196. # Strip trailing bits
  197. if not man & 1:
  198. t = trailtable[int(man & 255)]
  199. if not t:
  200. while not man & 255:
  201. man >>= 8
  202. exp += 8
  203. bc -= 8
  204. t = trailtable[int(man & 255)]
  205. man >>= t
  206. exp += t
  207. bc -= t
  208. # Bit count can be wrong if the input mantissa was 1 less than
  209. # a power of 2 and got rounded up, thereby adding an extra bit.
  210. # With trailing bits removed, all powers of two have mantissa 1,
  211. # so this is easy to check for.
  212. if man == 1:
  213. bc = 1
  214. return sign, man, exp, bc
  215. try:
  216. _exp_types = (int, long)
  217. except NameError:
  218. _exp_types = (int,)
  219. def strict_normalize(sign, man, exp, bc, prec, rnd):
  220. """Additional checks on the components of an mpf. Enable tests by setting
  221. the environment variable MPMATH_STRICT to Y."""
  222. assert type(man) == MPZ_TYPE
  223. assert type(bc) in _exp_types
  224. assert type(exp) in _exp_types
  225. assert bc == bitcount(man)
  226. return _normalize(sign, man, exp, bc, prec, rnd)
  227. def strict_normalize1(sign, man, exp, bc, prec, rnd):
  228. """Additional checks on the components of an mpf. Enable tests by setting
  229. the environment variable MPMATH_STRICT to Y."""
  230. assert type(man) == MPZ_TYPE
  231. assert type(bc) in _exp_types
  232. assert type(exp) in _exp_types
  233. assert bc == bitcount(man)
  234. assert (not man) or (man & 1)
  235. return _normalize1(sign, man, exp, bc, prec, rnd)
  236. if BACKEND == 'gmpy' and '_mpmath_normalize' in dir(gmpy):
  237. _normalize = gmpy._mpmath_normalize
  238. _normalize1 = gmpy._mpmath_normalize
  239. if BACKEND == 'sage':
  240. _normalize = _normalize1 = sage_utils.normalize
  241. if STRICT:
  242. normalize = strict_normalize
  243. normalize1 = strict_normalize1
  244. else:
  245. normalize = _normalize
  246. normalize1 = _normalize1
  247. #----------------------------------------------------------------------------#
  248. # Conversion functions #
  249. #----------------------------------------------------------------------------#
  250. def from_man_exp(man, exp, prec=None, rnd=round_fast):
  251. """Create raw mpf from (man, exp) pair. The mantissa may be signed.
  252. If no precision is specified, the mantissa is stored exactly."""
  253. man = MPZ(man)
  254. sign = 0
  255. if man < 0:
  256. sign = 1
  257. man = -man
  258. if man < 1024:
  259. bc = bctable[int(man)]
  260. else:
  261. bc = bitcount(man)
  262. if not prec:
  263. if not man:
  264. return fzero
  265. if not man & 1:
  266. if man & 2:
  267. return (sign, man >> 1, exp + 1, bc - 1)
  268. t = trailtable[int(man & 255)]
  269. if not t:
  270. while not man & 255:
  271. man >>= 8
  272. exp += 8
  273. bc -= 8
  274. t = trailtable[int(man & 255)]
  275. man >>= t
  276. exp += t
  277. bc -= t
  278. return (sign, man, exp, bc)
  279. return normalize(sign, man, exp, bc, prec, rnd)
  280. int_cache = dict((n, from_man_exp(n, 0)) for n in range(-10, 257))
  281. if BACKEND == 'gmpy' and '_mpmath_create' in dir(gmpy):
  282. from_man_exp = gmpy._mpmath_create
  283. if BACKEND == 'sage':
  284. from_man_exp = sage_utils.from_man_exp
  285. def from_int(n, prec=0, rnd=round_fast):
  286. """Create a raw mpf from an integer. If no precision is specified,
  287. the mantissa is stored exactly."""
  288. if not prec:
  289. if n in int_cache:
  290. return int_cache[n]
  291. return from_man_exp(n, 0, prec, rnd)
  292. def to_man_exp(s):
  293. """Return (man, exp) of a raw mpf. Raise an error if inf/nan."""
  294. sign, man, exp, bc = s
  295. if (not man) and exp:
  296. raise ValueError("mantissa and exponent are undefined for %s" % man)
  297. return man, exp
  298. def to_int(s, rnd=None):
  299. """Convert a raw mpf to the nearest int. Rounding is done down by
  300. default (same as int(float) in Python), but can be changed. If the
  301. input is inf/nan, an exception is raised."""
  302. sign, man, exp, bc = s
  303. if (not man) and exp:
  304. raise ValueError("cannot convert inf or nan to int")
  305. if exp >= 0:
  306. if sign:
  307. return (-man) << exp
  308. return man << exp
  309. # Make default rounding fast
  310. if not rnd:
  311. if sign:
  312. return -(man >> (-exp))
  313. else:
  314. return man >> (-exp)
  315. if sign:
  316. return round_int(-man, -exp, rnd)
  317. else:
  318. return round_int(man, -exp, rnd)
  319. def mpf_round_int(s, rnd):
  320. sign, man, exp, bc = s
  321. if (not man) and exp:
  322. return s
  323. if exp >= 0:
  324. return s
  325. mag = exp+bc
  326. if mag < 1:
  327. if rnd == round_ceiling:
  328. if sign: return fzero
  329. else: return fone
  330. elif rnd == round_floor:
  331. if sign: return fnone
  332. else: return fzero
  333. elif rnd == round_nearest:
  334. if mag < 0 or man == MPZ_ONE: return fzero
  335. elif sign: return fnone
  336. else: return fone
  337. else:
  338. raise NotImplementedError
  339. return mpf_pos(s, min(bc, mag), rnd)
  340. def mpf_floor(s, prec=0, rnd=round_fast):
  341. v = mpf_round_int(s, round_floor)
  342. if prec:
  343. v = mpf_pos(v, prec, rnd)
  344. return v
  345. def mpf_ceil(s, prec=0, rnd=round_fast):
  346. v = mpf_round_int(s, round_ceiling)
  347. if prec:
  348. v = mpf_pos(v, prec, rnd)
  349. return v
  350. def mpf_nint(s, prec=0, rnd=round_fast):
  351. v = mpf_round_int(s, round_nearest)
  352. if prec:
  353. v = mpf_pos(v, prec, rnd)
  354. return v
  355. def mpf_frac(s, prec=0, rnd=round_fast):
  356. return mpf_sub(s, mpf_floor(s), prec, rnd)
  357. def from_float(x, prec=53, rnd=round_fast):
  358. """Create a raw mpf from a Python float, rounding if necessary.
  359. If prec >= 53, the result is guaranteed to represent exactly the
  360. same number as the input. If prec is not specified, use prec=53."""
  361. # frexp only raises an exception for nan on some platforms
  362. if x != x:
  363. return fnan
  364. # in Python2.5 math.frexp gives an exception for float infinity
  365. # in Python2.6 it returns (float infinity, 0)
  366. try:
  367. m, e = math.frexp(x)
  368. except:
  369. if x == math_float_inf: return finf
  370. if x == -math_float_inf: return fninf
  371. return fnan
  372. if x == math_float_inf: return finf
  373. if x == -math_float_inf: return fninf
  374. return from_man_exp(int(m*(1<<53)), e-53, prec, rnd)
  375. def from_npfloat(x, prec=113, rnd=round_fast):
  376. """Create a raw mpf from a numpy float, rounding if necessary.
  377. If prec >= 113, the result is guaranteed to represent exactly the
  378. same number as the input. If prec is not specified, use prec=113."""
  379. y = float(x)
  380. if x == y: # ldexp overflows for float16
  381. return from_float(y, prec, rnd)
  382. import numpy as np
  383. if np.isfinite(x):
  384. m, e = np.frexp(x)
  385. return from_man_exp(int(np.ldexp(m, 113)), int(e-113), prec, rnd)
  386. if np.isposinf(x): return finf
  387. if np.isneginf(x): return fninf
  388. return fnan
  389. def from_Decimal(x, prec=None, rnd=round_fast):
  390. """Create a raw mpf from a Decimal, rounding if necessary.
  391. If prec is not specified, use the equivalent bit precision
  392. of the number of significant digits in x."""
  393. if x.is_nan(): return fnan
  394. if x.is_infinite(): return fninf if x.is_signed() else finf
  395. if prec is None:
  396. prec = int(len(x.as_tuple()[1])*3.3219280948873626)
  397. return from_str(str(x), prec, rnd)
  398. def to_float(s, strict=False, rnd=round_fast):
  399. """
  400. Convert a raw mpf to a Python float. The result is exact if the
  401. bitcount of s is <= 53 and no underflow/overflow occurs.
  402. If the number is too large or too small to represent as a regular
  403. float, it will be converted to inf or 0.0. Setting strict=True
  404. forces an OverflowError to be raised instead.
  405. Warning: with a directed rounding mode, the correct nearest representable
  406. floating-point number in the specified direction might not be computed
  407. in case of overflow or (gradual) underflow.
  408. """
  409. sign, man, exp, bc = s
  410. if not man:
  411. if s == fzero: return 0.0
  412. if s == finf: return math_float_inf
  413. if s == fninf: return -math_float_inf
  414. return math_float_inf/math_float_inf
  415. if bc > 53:
  416. sign, man, exp, bc = normalize1(sign, man, exp, bc, 53, rnd)
  417. if sign:
  418. man = -man
  419. try:
  420. return math.ldexp(man, exp)
  421. except OverflowError:
  422. if strict:
  423. raise
  424. # Overflow to infinity
  425. if exp + bc > 0:
  426. if sign:
  427. return -math_float_inf
  428. else:
  429. return math_float_inf
  430. # Underflow to zero
  431. return 0.0
  432. def from_rational(p, q, prec, rnd=round_fast):
  433. """Create a raw mpf from a rational number p/q, round if
  434. necessary."""
  435. return mpf_div(from_int(p), from_int(q), prec, rnd)
  436. def to_rational(s):
  437. """Convert a raw mpf to a rational number. Return integers (p, q)
  438. such that s = p/q exactly."""
  439. sign, man, exp, bc = s
  440. if sign:
  441. man = -man
  442. if bc == -1:
  443. raise ValueError("cannot convert %s to a rational number" % man)
  444. if exp >= 0:
  445. return man * (1<<exp), 1
  446. else:
  447. return man, 1<<(-exp)
  448. def to_fixed(s, prec):
  449. """Convert a raw mpf to a fixed-point big integer"""
  450. sign, man, exp, bc = s
  451. offset = exp + prec
  452. if sign:
  453. if offset >= 0: return (-man) << offset
  454. else: return (-man) >> (-offset)
  455. else:
  456. if offset >= 0: return man << offset
  457. else: return man >> (-offset)
  458. ##############################################################################
  459. ##############################################################################
  460. #----------------------------------------------------------------------------#
  461. # Arithmetic operations, etc. #
  462. #----------------------------------------------------------------------------#
  463. def mpf_rand(prec):
  464. """Return a raw mpf chosen randomly from [0, 1), with prec bits
  465. in the mantissa."""
  466. global getrandbits
  467. if not getrandbits:
  468. import random
  469. getrandbits = random.getrandbits
  470. return from_man_exp(getrandbits(prec), -prec, prec, round_floor)
  471. def mpf_eq(s, t):
  472. """Test equality of two raw mpfs. This is simply tuple comparison
  473. unless either number is nan, in which case the result is False."""
  474. if not s[1] or not t[1]:
  475. if s == fnan or t == fnan:
  476. return False
  477. return s == t
  478. def mpf_hash(s):
  479. # Duplicate the new hash algorithm introduces in Python 3.2.
  480. if sys.version_info >= (3, 2):
  481. ssign, sman, sexp, sbc = s
  482. # Handle special numbers
  483. if not sman:
  484. if s == fnan: return sys.hash_info.nan
  485. if s == finf: return sys.hash_info.inf
  486. if s == fninf: return -sys.hash_info.inf
  487. h = sman % HASH_MODULUS
  488. if sexp >= 0:
  489. sexp = sexp % HASH_BITS
  490. else:
  491. sexp = HASH_BITS - 1 - ((-1 - sexp) % HASH_BITS)
  492. h = (h << sexp) % HASH_MODULUS
  493. if ssign: h = -h
  494. if h == -1: h == -2
  495. return int(h)
  496. else:
  497. try:
  498. # Try to be compatible with hash values for floats and ints
  499. return hash(to_float(s, strict=1))
  500. except OverflowError:
  501. # We must unfortunately sacrifice compatibility with ints here.
  502. # We could do hash(man << exp) when the exponent is positive, but
  503. # this would cause unreasonable inefficiency for large numbers.
  504. return hash(s)
  505. def mpf_cmp(s, t):
  506. """Compare the raw mpfs s and t. Return -1 if s < t, 0 if s == t,
  507. and 1 if s > t. (Same convention as Python's cmp() function.)"""
  508. # In principle, a comparison amounts to determining the sign of s-t.
  509. # A full subtraction is relatively slow, however, so we first try to
  510. # look at the components.
  511. ssign, sman, sexp, sbc = s
  512. tsign, tman, texp, tbc = t
  513. # Handle zeros and special numbers
  514. if not sman or not tman:
  515. if s == fzero: return -mpf_sign(t)
  516. if t == fzero: return mpf_sign(s)
  517. if s == t: return 0
  518. # Follow same convention as Python's cmp for float nan
  519. if t == fnan: return 1
  520. if s == finf: return 1
  521. if t == fninf: return 1
  522. return -1
  523. # Different sides of zero
  524. if ssign != tsign:
  525. if not ssign: return 1
  526. return -1
  527. # This reduces to direct integer comparison
  528. if sexp == texp:
  529. if sman == tman:
  530. return 0
  531. if sman > tman:
  532. if ssign: return -1
  533. else: return 1
  534. else:
  535. if ssign: return 1
  536. else: return -1
  537. # Check position of the highest set bit in each number. If
  538. # different, there is certainly an inequality.
  539. a = sbc + sexp
  540. b = tbc + texp
  541. if ssign:
  542. if a < b: return 1
  543. if a > b: return -1
  544. else:
  545. if a < b: return -1
  546. if a > b: return 1
  547. # Both numbers have the same highest bit. Subtract to find
  548. # how the lower bits compare.
  549. delta = mpf_sub(s, t, 5, round_floor)
  550. if delta[0]:
  551. return -1
  552. return 1
  553. def mpf_lt(s, t):
  554. if s == fnan or t == fnan:
  555. return False
  556. return mpf_cmp(s, t) < 0
  557. def mpf_le(s, t):
  558. if s == fnan or t == fnan:
  559. return False
  560. return mpf_cmp(s, t) <= 0
  561. def mpf_gt(s, t):
  562. if s == fnan or t == fnan:
  563. return False
  564. return mpf_cmp(s, t) > 0
  565. def mpf_ge(s, t):
  566. if s == fnan or t == fnan:
  567. return False
  568. return mpf_cmp(s, t) >= 0
  569. def mpf_min_max(seq):
  570. min = max = seq[0]
  571. for x in seq[1:]:
  572. if mpf_lt(x, min): min = x
  573. if mpf_gt(x, max): max = x
  574. return min, max
  575. def mpf_pos(s, prec=0, rnd=round_fast):
  576. """Calculate 0+s for a raw mpf (i.e., just round s to the specified
  577. precision)."""
  578. if prec:
  579. sign, man, exp, bc = s
  580. if (not man) and exp:
  581. return s
  582. return normalize1(sign, man, exp, bc, prec, rnd)
  583. return s
  584. def mpf_neg(s, prec=None, rnd=round_fast):
  585. """Negate a raw mpf (return -s), rounding the result to the
  586. specified precision. The prec argument can be omitted to do the
  587. operation exactly."""
  588. sign, man, exp, bc = s
  589. if not man:
  590. if exp:
  591. if s == finf: return fninf
  592. if s == fninf: return finf
  593. return s
  594. if not prec:
  595. return (1-sign, man, exp, bc)
  596. return normalize1(1-sign, man, exp, bc, prec, rnd)
  597. def mpf_abs(s, prec=None, rnd=round_fast):
  598. """Return abs(s) of the raw mpf s, rounded to the specified
  599. precision. The prec argument can be omitted to generate an
  600. exact result."""
  601. sign, man, exp, bc = s
  602. if (not man) and exp:
  603. if s == fninf:
  604. return finf
  605. return s
  606. if not prec:
  607. if sign:
  608. return (0, man, exp, bc)
  609. return s
  610. return normalize1(0, man, exp, bc, prec, rnd)
  611. def mpf_sign(s):
  612. """Return -1, 0, or 1 (as a Python int, not a raw mpf) depending on
  613. whether s is negative, zero, or positive. (Nan is taken to give 0.)"""
  614. sign, man, exp, bc = s
  615. if not man:
  616. if s == finf: return 1
  617. if s == fninf: return -1
  618. return 0
  619. return (-1) ** sign
  620. def mpf_add(s, t, prec=0, rnd=round_fast, _sub=0):
  621. """
  622. Add the two raw mpf values s and t.
  623. With prec=0, no rounding is performed. Note that this can
  624. produce a very large mantissa (potentially too large to fit
  625. in memory) if exponents are far apart.
  626. """
  627. ssign, sman, sexp, sbc = s
  628. tsign, tman, texp, tbc = t
  629. tsign ^= _sub
  630. # Standard case: two nonzero, regular numbers
  631. if sman and tman:
  632. offset = sexp - texp
  633. if offset:
  634. if offset > 0:
  635. # Outside precision range; only need to perturb
  636. if offset > 100 and prec:
  637. delta = sbc + sexp - tbc - texp
  638. if delta > prec + 4:
  639. offset = prec + 4
  640. sman <<= offset
  641. if tsign == ssign: sman += 1
  642. else: sman -= 1
  643. return normalize1(ssign, sman, sexp-offset,
  644. bitcount(sman), prec, rnd)
  645. # Add
  646. if ssign == tsign:
  647. man = tman + (sman << offset)
  648. # Subtract
  649. else:
  650. if ssign: man = tman - (sman << offset)
  651. else: man = (sman << offset) - tman
  652. if man >= 0:
  653. ssign = 0
  654. else:
  655. man = -man
  656. ssign = 1
  657. bc = bitcount(man)
  658. return normalize1(ssign, man, texp, bc, prec or bc, rnd)
  659. elif offset < 0:
  660. # Outside precision range; only need to perturb
  661. if offset < -100 and prec:
  662. delta = tbc + texp - sbc - sexp
  663. if delta > prec + 4:
  664. offset = prec + 4
  665. tman <<= offset
  666. if ssign == tsign: tman += 1
  667. else: tman -= 1
  668. return normalize1(tsign, tman, texp-offset,
  669. bitcount(tman), prec, rnd)
  670. # Add
  671. if ssign == tsign:
  672. man = sman + (tman << -offset)
  673. # Subtract
  674. else:
  675. if tsign: man = sman - (tman << -offset)
  676. else: man = (tman << -offset) - sman
  677. if man >= 0:
  678. ssign = 0
  679. else:
  680. man = -man
  681. ssign = 1
  682. bc = bitcount(man)
  683. return normalize1(ssign, man, sexp, bc, prec or bc, rnd)
  684. # Equal exponents; no shifting necessary
  685. if ssign == tsign:
  686. man = tman + sman
  687. else:
  688. if ssign: man = tman - sman
  689. else: man = sman - tman
  690. if man >= 0:
  691. ssign = 0
  692. else:
  693. man = -man
  694. ssign = 1
  695. bc = bitcount(man)
  696. return normalize(ssign, man, texp, bc, prec or bc, rnd)
  697. # Handle zeros and special numbers
  698. if _sub:
  699. t = mpf_neg(t)
  700. if not sman:
  701. if sexp:
  702. if s == t or tman or not texp:
  703. return s
  704. return fnan
  705. if tman:
  706. return normalize1(tsign, tman, texp, tbc, prec or tbc, rnd)
  707. return t
  708. if texp:
  709. return t
  710. if sman:
  711. return normalize1(ssign, sman, sexp, sbc, prec or sbc, rnd)
  712. return s
  713. def mpf_sub(s, t, prec=0, rnd=round_fast):
  714. """Return the difference of two raw mpfs, s-t. This function is
  715. simply a wrapper of mpf_add that changes the sign of t."""
  716. return mpf_add(s, t, prec, rnd, 1)
  717. def mpf_sum(xs, prec=0, rnd=round_fast, absolute=False):
  718. """
  719. Sum a list of mpf values efficiently and accurately
  720. (typically no temporary roundoff occurs). If prec=0,
  721. the final result will not be rounded either.
  722. There may be roundoff error or cancellation if extremely
  723. large exponent differences occur.
  724. With absolute=True, sums the absolute values.
  725. """
  726. man = 0
  727. exp = 0
  728. max_extra_prec = prec*2 or 1000000 # XXX
  729. special = None
  730. for x in xs:
  731. xsign, xman, xexp, xbc = x
  732. if xman:
  733. if xsign and not absolute:
  734. xman = -xman
  735. delta = xexp - exp
  736. if xexp >= exp:
  737. # x much larger than existing sum?
  738. # first: quick test
  739. if (delta > max_extra_prec) and \
  740. ((not man) or delta-bitcount(abs(man)) > max_extra_prec):
  741. man = xman
  742. exp = xexp
  743. else:
  744. man += (xman << delta)
  745. else:
  746. delta = -delta
  747. # x much smaller than existing sum?
  748. if delta-xbc > max_extra_prec:
  749. if not man:
  750. man, exp = xman, xexp
  751. else:
  752. man = (man << delta) + xman
  753. exp = xexp
  754. elif xexp:
  755. if absolute:
  756. x = mpf_abs(x)
  757. special = mpf_add(special or fzero, x, 1)
  758. # Will be inf or nan
  759. if special:
  760. return special
  761. return from_man_exp(man, exp, prec, rnd)
  762. def gmpy_mpf_mul(s, t, prec=0, rnd=round_fast):
  763. """Multiply two raw mpfs"""
  764. ssign, sman, sexp, sbc = s
  765. tsign, tman, texp, tbc = t
  766. sign = ssign ^ tsign
  767. man = sman*tman
  768. if man:
  769. bc = bitcount(man)
  770. if prec:
  771. return normalize1(sign, man, sexp+texp, bc, prec, rnd)
  772. else:
  773. return (sign, man, sexp+texp, bc)
  774. s_special = (not sman) and sexp
  775. t_special = (not tman) and texp
  776. if not s_special and not t_special:
  777. return fzero
  778. if fnan in (s, t): return fnan
  779. if (not tman) and texp: s, t = t, s
  780. if t == fzero: return fnan
  781. return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)]
  782. def gmpy_mpf_mul_int(s, n, prec, rnd=round_fast):
  783. """Multiply by a Python integer."""
  784. sign, man, exp, bc = s
  785. if not man:
  786. return mpf_mul(s, from_int(n), prec, rnd)
  787. if not n:
  788. return fzero
  789. if n < 0:
  790. sign ^= 1
  791. n = -n
  792. man *= n
  793. return normalize(sign, man, exp, bitcount(man), prec, rnd)
  794. def python_mpf_mul(s, t, prec=0, rnd=round_fast):
  795. """Multiply two raw mpfs"""
  796. ssign, sman, sexp, sbc = s
  797. tsign, tman, texp, tbc = t
  798. sign = ssign ^ tsign
  799. man = sman*tman
  800. if man:
  801. bc = sbc + tbc - 1
  802. bc += int(man>>bc)
  803. if prec:
  804. return normalize1(sign, man, sexp+texp, bc, prec, rnd)
  805. else:
  806. return (sign, man, sexp+texp, bc)
  807. s_special = (not sman) and sexp
  808. t_special = (not tman) and texp
  809. if not s_special and not t_special:
  810. return fzero
  811. if fnan in (s, t): return fnan
  812. if (not tman) and texp: s, t = t, s
  813. if t == fzero: return fnan
  814. return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)]
  815. def python_mpf_mul_int(s, n, prec, rnd=round_fast):
  816. """Multiply by a Python integer."""
  817. sign, man, exp, bc = s
  818. if not man:
  819. return mpf_mul(s, from_int(n), prec, rnd)
  820. if not n:
  821. return fzero
  822. if n < 0:
  823. sign ^= 1
  824. n = -n
  825. man *= n
  826. # Generally n will be small
  827. if n < 1024:
  828. bc += bctable[int(n)] - 1
  829. else:
  830. bc += bitcount(n) - 1
  831. bc += int(man>>bc)
  832. return normalize(sign, man, exp, bc, prec, rnd)
  833. if BACKEND == 'gmpy':
  834. mpf_mul = gmpy_mpf_mul
  835. mpf_mul_int = gmpy_mpf_mul_int
  836. else:
  837. mpf_mul = python_mpf_mul
  838. mpf_mul_int = python_mpf_mul_int
  839. def mpf_shift(s, n):
  840. """Quickly multiply the raw mpf s by 2**n without rounding."""
  841. sign, man, exp, bc = s
  842. if not man:
  843. return s
  844. return sign, man, exp+n, bc
  845. def mpf_frexp(x):
  846. """Convert x = y*2**n to (y, n) with abs(y) in [0.5, 1) if nonzero"""
  847. sign, man, exp, bc = x
  848. if not man:
  849. if x == fzero:
  850. return (fzero, 0)
  851. else:
  852. raise ValueError
  853. return mpf_shift(x, -bc-exp), bc+exp
  854. def mpf_div(s, t, prec, rnd=round_fast):
  855. """Floating-point division"""
  856. ssign, sman, sexp, sbc = s
  857. tsign, tman, texp, tbc = t
  858. if not sman or not tman:
  859. if s == fzero:
  860. if t == fzero: raise ZeroDivisionError
  861. if t == fnan: return fnan
  862. return fzero
  863. if t == fzero:
  864. raise ZeroDivisionError
  865. s_special = (not sman) and sexp
  866. t_special = (not tman) and texp
  867. if s_special and t_special:
  868. return fnan
  869. if s == fnan or t == fnan:
  870. return fnan
  871. if not t_special:
  872. if t == fzero:
  873. return fnan
  874. return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)]
  875. return fzero
  876. sign = ssign ^ tsign
  877. if tman == 1:
  878. return normalize1(sign, sman, sexp-texp, sbc, prec, rnd)
  879. # Same strategy as for addition: if there is a remainder, perturb
  880. # the result a few bits outside the precision range before rounding
  881. extra = prec - sbc + tbc + 5
  882. if extra < 5:
  883. extra = 5
  884. quot, rem = divmod(sman<<extra, tman)
  885. if rem:
  886. quot = (quot<<1) + 1
  887. extra += 1
  888. return normalize1(sign, quot, sexp-texp-extra, bitcount(quot), prec, rnd)
  889. return normalize(sign, quot, sexp-texp-extra, bitcount(quot), prec, rnd)
  890. def mpf_rdiv_int(n, t, prec, rnd=round_fast):
  891. """Floating-point division n/t with a Python integer as numerator"""
  892. sign, man, exp, bc = t
  893. if not n or not man:
  894. return mpf_div(from_int(n), t, prec, rnd)
  895. if n < 0:
  896. sign ^= 1
  897. n = -n
  898. extra = prec + bc + 5
  899. quot, rem = divmod(n<<extra, man)
  900. if rem:
  901. quot = (quot<<1) + 1
  902. extra += 1
  903. return normalize1(sign, quot, -exp-extra, bitcount(quot), prec, rnd)
  904. return normalize(sign, quot, -exp-extra, bitcount(quot), prec, rnd)
  905. def mpf_mod(s, t, prec, rnd=round_fast):
  906. ssign, sman, sexp, sbc = s
  907. tsign, tman, texp, tbc = t
  908. if ((not sman) and sexp) or ((not tman) and texp):
  909. return fnan
  910. # Important special case: do nothing if t is larger
  911. if ssign == tsign and texp > sexp+sbc:
  912. return s
  913. # Another important special case: this allows us to do e.g. x % 1.0
  914. # to find the fractional part of x, and it will work when x is huge.
  915. if tman == 1 and sexp > texp+tbc:
  916. return fzero
  917. base = min(sexp, texp)
  918. sman = (-1)**ssign * sman
  919. tman = (-1)**tsign * tman
  920. man = (sman << (sexp-base)) % (tman << (texp-base))
  921. if man >= 0:
  922. sign = 0
  923. else:
  924. man = -man
  925. sign = 1
  926. return normalize(sign, man, base, bitcount(man), prec, rnd)
  927. reciprocal_rnd = {
  928. round_down : round_up,
  929. round_up : round_down,
  930. round_floor : round_ceiling,
  931. round_ceiling : round_floor,
  932. round_nearest : round_nearest
  933. }
  934. negative_rnd = {
  935. round_down : round_down,
  936. round_up : round_up,
  937. round_floor : round_ceiling,
  938. round_ceiling : round_floor,
  939. round_nearest : round_nearest
  940. }
  941. def mpf_pow_int(s, n, prec, rnd=round_fast):
  942. """Compute s**n, where s is a raw mpf and n is a Python integer."""
  943. sign, man, exp, bc = s
  944. if (not man) and exp:
  945. if s == finf:
  946. if n > 0: return s
  947. if n == 0: return fnan
  948. return fzero
  949. if s == fninf:
  950. if n > 0: return [finf, fninf][n & 1]
  951. if n == 0: return fnan
  952. return fzero
  953. return fnan
  954. n = int(n)
  955. if n == 0: return fone
  956. if n == 1: return mpf_pos(s, prec, rnd)
  957. if n == 2:
  958. _, man, exp, bc = s
  959. if not man:
  960. return fzero
  961. man = man*man
  962. if man == 1:
  963. return (0, MPZ_ONE, exp+exp, 1)
  964. bc = bc + bc - 2
  965. bc += bctable[int(man>>bc)]
  966. return normalize1(0, man, exp+exp, bc, prec, rnd)
  967. if n == -1: return mpf_div(fone, s, prec, rnd)
  968. if n < 0:
  969. inverse = mpf_pow_int(s, -n, prec+5, reciprocal_rnd[rnd])
  970. return mpf_div(fone, inverse, prec, rnd)
  971. result_sign = sign & n
  972. # Use exact integer power when the exact mantissa is small
  973. if man == 1:
  974. return (result_sign, MPZ_ONE, exp*n, 1)
  975. if bc*n < 1000:
  976. man **= n
  977. return normalize1(result_sign, man, exp*n, bitcount(man), prec, rnd)
  978. # Use directed rounding all the way through to maintain rigorous
  979. # bounds for interval arithmetic
  980. rounds_down = (rnd == round_nearest) or \
  981. shifts_down[rnd][result_sign]
  982. # Now we perform binary exponentiation. Need to estimate precision
  983. # to avoid rounding errors from temporary operations. Roughly log_2(n)
  984. # operations are performed.
  985. workprec = prec + 4*bitcount(n) + 4
  986. _, pm, pe, pbc = fone
  987. while 1:
  988. if n & 1:
  989. pm = pm*man
  990. pe = pe+exp
  991. pbc += bc - 2
  992. pbc = pbc + bctable[int(pm >> pbc)]
  993. if pbc > workprec:
  994. if rounds_down:
  995. pm = pm >> (pbc-workprec)
  996. else:
  997. pm = -((-pm) >> (pbc-workprec))
  998. pe += pbc - workprec
  999. pbc = workprec
  1000. n -= 1
  1001. if not n:
  1002. break
  1003. man = man*man
  1004. exp = exp+exp
  1005. bc = bc + bc - 2
  1006. bc = bc + bctable[int(man >> bc)]
  1007. if bc > workprec:
  1008. if rounds_down:
  1009. man = man >> (bc-workprec)
  1010. else:
  1011. man = -((-man) >> (bc-workprec))
  1012. exp += bc - workprec
  1013. bc = workprec
  1014. n = n // 2
  1015. return normalize(result_sign, pm, pe, pbc, prec, rnd)
  1016. def mpf_perturb(x, eps_sign, prec, rnd):
  1017. """
  1018. For nonzero x, calculate x + eps with directed rounding, where
  1019. eps < prec relatively and eps has the given sign (0 for
  1020. positive, 1 for negative).
  1021. With rounding to nearest, this is taken to simply normalize
  1022. x to the given precision.
  1023. """
  1024. if rnd == round_nearest:
  1025. return mpf_pos(x, prec, rnd)
  1026. sign, man, exp, bc = x
  1027. eps = (eps_sign, MPZ_ONE, exp+bc-prec-1, 1)
  1028. if sign:
  1029. away = (rnd in (round_down, round_ceiling)) ^ eps_sign
  1030. else:
  1031. away = (rnd in (round_up, round_ceiling)) ^ eps_sign
  1032. if away:
  1033. return mpf_add(x, eps, prec, rnd)
  1034. else:
  1035. return mpf_pos(x, prec, rnd)
  1036. #----------------------------------------------------------------------------#
  1037. # Radix conversion #
  1038. #----------------------------------------------------------------------------#
  1039. def to_digits_exp(s, dps):
  1040. """Helper function for representing the floating-point number s as
  1041. a decimal with dps digits. Returns (sign, string, exponent) where
  1042. sign is '' or '-', string is the digit string, and exponent is
  1043. the decimal exponent as an int.
  1044. If inexact, the decimal representation is rounded toward zero."""
  1045. # Extract sign first so it doesn't mess up the string digit count
  1046. if s[0]:
  1047. sign = '-'
  1048. s = mpf_neg(s)
  1049. else:
  1050. sign = ''
  1051. _sign, man, exp, bc = s
  1052. if not man:
  1053. return '', '0', 0
  1054. bitprec = int(dps * math.log(10,2)) + 10
  1055. # Cut down to size
  1056. # TODO: account for precision when doing this
  1057. exp_from_1 = exp + bc
  1058. if abs(exp_from_1) > 3500:
  1059. from .libelefun import mpf_ln2, mpf_ln10
  1060. # Set b = int(exp * log(2)/log(10))
  1061. # If exp is huge, we must use high-precision arithmetic to
  1062. # find the nearest power of ten
  1063. expprec = bitcount(abs(exp)) + 5
  1064. tmp = from_int(exp)
  1065. tmp = mpf_mul(tmp, mpf_ln2(expprec))
  1066. tmp = mpf_div(tmp, mpf_ln10(expprec), expprec)
  1067. b = to_int(tmp)
  1068. s = mpf_div(s, mpf_pow_int(ften, b, bitprec), bitprec)
  1069. _sign, man, exp, bc = s
  1070. exponent = b
  1071. else:
  1072. exponent = 0
  1073. # First, calculate mantissa digits by converting to a binary
  1074. # fixed-point number and then converting that number to
  1075. # a decimal fixed-point number.
  1076. fixprec = max(bitprec - exp - bc, 0)
  1077. fixdps = int(fixprec / math.log(10,2) + 0.5)
  1078. sf = to_fixed(s, fixprec)
  1079. sd = bin_to_radix(sf, fixprec, 10, fixdps)
  1080. digits = numeral(sd, base=10, size=dps)
  1081. exponent += len(digits) - fixdps - 1
  1082. return sign, digits, exponent
  1083. def to_str(s, dps, strip_zeros=True, min_fixed=None, max_fixed=None,
  1084. show_zero_exponent=False):
  1085. """
  1086. Convert a raw mpf to a decimal floating-point literal with at
  1087. most `dps` decimal digits in the mantissa (not counting extra zeros
  1088. that may be inserted for visual purposes).
  1089. The number will be printed in fixed-point format if the position
  1090. of the leading digit is strictly between min_fixed
  1091. (default = min(-dps/3,-5)) and max_fixed (default = dps).
  1092. To force fixed-point format always, set min_fixed = -inf,
  1093. max_fixed = +inf. To force floating-point format, set
  1094. min_fixed >= max_fixed.
  1095. The literal is formatted so that it can be parsed back to a number
  1096. by to_str, float() or Decimal().
  1097. """
  1098. # Special numbers
  1099. if not s[1]:
  1100. if s == fzero:
  1101. if dps: t = '0.0'
  1102. else: t = '.0'
  1103. if show_zero_exponent:
  1104. t += 'e+0'
  1105. return t
  1106. if s == finf: return '+inf'
  1107. if s == fninf: return '-inf'
  1108. if s == fnan: return 'nan'
  1109. raise ValueError
  1110. if min_fixed is None: min_fixed = min(-(dps//3), -5)
  1111. if max_fixed is None: max_fixed = dps
  1112. # to_digits_exp rounds to floor.
  1113. # This sometimes kills some instances of "...00001"
  1114. sign, digits, exponent = to_digits_exp(s, dps+3)
  1115. # No digits: show only .0; round exponent to nearest
  1116. if not dps:
  1117. if digits[0] in '56789':
  1118. exponent += 1
  1119. digits = ".0"
  1120. else:
  1121. # Rounding up kills some instances of "...99999"
  1122. if len(digits) > dps and digits[dps] in '56789':
  1123. digits = digits[:dps]
  1124. i = dps - 1
  1125. while i >= 0 and digits[i] == '9':
  1126. i -= 1
  1127. if i >= 0:
  1128. digits = digits[:i] + str(int(digits[i]) + 1) + '0' * (dps - i - 1)
  1129. else:
  1130. digits = '1' + '0' * (dps - 1)
  1131. exponent += 1
  1132. else:
  1133. digits = digits[:dps]
  1134. # Prettify numbers close to unit magnitude
  1135. if min_fixed < exponent < max_fixed:
  1136. if exponent < 0:
  1137. digits = ("0"*int(-exponent)) + digits
  1138. split = 1
  1139. else:
  1140. split = exponent + 1
  1141. if split > dps:
  1142. digits += "0"*(split-dps)
  1143. exponent = 0
  1144. else:
  1145. split = 1
  1146. digits = (digits[:split] + "." + digits[split:])
  1147. if strip_zeros:
  1148. # Clean up trailing zeros
  1149. digits = digits.rstrip('0')
  1150. if digits[-1] == ".":
  1151. digits += "0"
  1152. if exponent == 0 and dps and not show_zero_exponent: return sign + digits
  1153. if exponent >= 0: return sign + digits + "e+" + str(exponent)
  1154. if exponent < 0: return sign + digits + "e" + str(exponent)
  1155. def str_to_man_exp(x, base=10):
  1156. """Helper function for from_str."""
  1157. x = x.lower().rstrip('l')
  1158. # Verify that the input is a valid float literal
  1159. float(x)
  1160. # Split into mantissa, exponent
  1161. parts = x.split('e')
  1162. if len(parts) == 1:
  1163. exp = 0
  1164. else: # == 2
  1165. x = parts[0]
  1166. exp = int(parts[1])
  1167. # Look for radix point in mantissa
  1168. parts = x.split('.')
  1169. if len(parts) == 2:
  1170. a, b = parts[0], parts[1].rstrip('0')
  1171. exp -= len(b)
  1172. x = a + b
  1173. x = MPZ(int(x, base))
  1174. return x, exp
  1175. special_str = {'inf':finf, '+inf':finf, '-inf':fninf, 'nan':fnan}
  1176. def from_str(x, prec, rnd=round_fast):
  1177. """Create a raw mpf from a decimal literal, rounding in the
  1178. specified direction if the input number cannot be represented
  1179. exactly as a binary floating-point number with the given number of
  1180. bits. The literal syntax accepted is the same as for Python
  1181. floats.
  1182. TODO: the rounding does not work properly for large exponents.
  1183. """
  1184. x = x.lower().strip()
  1185. if x in special_str:
  1186. return special_str[x]
  1187. if '/' in x:
  1188. p, q = x.split('/')
  1189. p, q = p.rstrip('l'), q.rstrip('l')
  1190. return from_rational(int(p), int(q), prec, rnd)
  1191. man, exp = str_to_man_exp(x, base=10)
  1192. # XXX: appropriate cutoffs & track direction
  1193. # note no factors of 5
  1194. if abs(exp) > 400:
  1195. s = from_int(man, prec+10)
  1196. s = mpf_mul(s, mpf_pow_int(ften, exp, prec+10), prec, rnd)
  1197. else:
  1198. if exp >= 0:
  1199. s = from_int(man * 10**exp, prec, rnd)
  1200. else:
  1201. s = from_rational(man, 10**-exp, prec, rnd)
  1202. return s
  1203. # Binary string conversion. These are currently mainly used for debugging
  1204. # and could use some improvement in the future
  1205. def from_bstr(x):
  1206. man, exp = str_to_man_exp(x, base=2)
  1207. man = MPZ(man)
  1208. sign = 0
  1209. if man < 0:
  1210. man = -man
  1211. sign = 1
  1212. bc = bitcount(man)
  1213. return normalize(sign, man, exp, bc, bc, round_floor)
  1214. def to_bstr(x):
  1215. sign, man, exp, bc = x
  1216. return ['','-'][sign] + numeral(man, size=bitcount(man), base=2) + ("e%i" % exp)
  1217. #----------------------------------------------------------------------------#
  1218. # Square roots #
  1219. #----------------------------------------------------------------------------#
  1220. def mpf_sqrt(s, prec, rnd=round_fast):
  1221. """
  1222. Compute the square root of a nonnegative mpf value. The
  1223. result is correctly rounded.
  1224. """
  1225. sign, man, exp, bc = s
  1226. if sign:
  1227. raise ComplexResult("square root of a negative number")
  1228. if not man:
  1229. return s
  1230. if exp & 1:
  1231. exp -= 1
  1232. man <<= 1
  1233. bc += 1
  1234. elif man == 1:
  1235. return normalize1(sign, man, exp//2, bc, prec, rnd)
  1236. shift = max(4, 2*prec-bc+4)
  1237. shift += shift & 1
  1238. if rnd in 'fd':
  1239. man = isqrt(man<<shift)
  1240. else:
  1241. man, rem = sqrtrem(man<<shift)
  1242. # Perturb up
  1243. if rem:
  1244. man = (man<<1)+1
  1245. shift += 2
  1246. return from_man_exp(man, (exp-shift)//2, prec, rnd)
  1247. def mpf_hypot(x, y, prec, rnd=round_fast):
  1248. """Compute the Euclidean norm sqrt(x**2 + y**2) of two raw mpfs
  1249. x and y."""
  1250. if y == fzero: return mpf_abs(x, prec, rnd)
  1251. if x == fzero: return mpf_abs(y, prec, rnd)
  1252. hypot2 = mpf_add(mpf_mul(x,x), mpf_mul(y,y), prec+4)
  1253. return mpf_sqrt(hypot2, prec, rnd)
  1254. if BACKEND == 'sage':
  1255. try:
  1256. import sage.libs.mpmath.ext_libmp as ext_lib
  1257. mpf_add = ext_lib.mpf_add
  1258. mpf_sub = ext_lib.mpf_sub
  1259. mpf_mul = ext_lib.mpf_mul
  1260. mpf_div = ext_lib.mpf_div
  1261. mpf_sqrt = ext_lib.mpf_sqrt
  1262. except ImportError:
  1263. pass