4

I am using python and have something like this-

a=3.472556691305291e-97
b=2.0842803001689662e-120

c=a/(a+b)
print(c)

I am getting value=1.0 . But I want the exact answer.Is there some way I can improve my accuracy here?

Noober
  • 1,516
  • 4
  • 22
  • 48
  • what is the desired type of the result? the exact fraction equals to `1.0` as a float: `float(Fraction(1736278345652645500000000000000000000000, 1736278345652645500000010421401500844831)) == 1` – jfs Sep 30 '15 at 14:54
  • The desired type is float only – Noober Sep 30 '15 at 15:24
  • 1
    If the result is `float` then `1.0` is the best you can get. – jfs Sep 30 '15 at 15:27

1 Answers1

3

You can use an external library, such as mpmath, to get arbitrary precision floating point numbers.

Use the mpf type for the numbers, as shown in the examples in the documentation:

>>> mpf(4)
mpf('4.0')
>>> mpf(2.5)
mpf('2.5')
>>> mpf("1.25e6")
mpf('1250000.0')
>>> mpf(mpf(2))
mpf('2.0')
>>> mpf("inf")
mpf('+inf')
  • 1
    what is the reason not to use `decimal` or `fractions` module from stdlib here? – jfs Sep 30 '15 at 14:42