Search code examples
pythonmathcalculus

How can I get more exact decimal values in Python


from math import sqrt


a=1e-8
b=10
c=1e-8

x1 = ((-b)-sqrt((b**2)-(4*a*c)))/(2*a)
x2 = ((-b)+sqrt((b**2)-(4*a*c)))/(2*a)

print 'x1 = {}'.format(x1)
print 'x2 = {}'.format(x2)

print (4*a*c)
print (sqrt(b**2-4*a*c))
print b**2
print 2*a

When I run the program, this returns:

x1 = -1e+09
x2 = 0.0

4e-16
10.0
100.0
2e-08

What I need is for x2 to be equal to -1e-9.

The problem seems to be with the

sqrt((b**2)-(4*a*c))

as it gives 10 as a result, obviously because 4*(10^-8)*(10^-8) is almost equal to 0, and is considered 0 by python.

This results in:

sqrt((b**2)-(4*a*c)) = sqrt(b**2) = sqrt(10**2) = 10

Any help would be greatly appreciated


Solution

  • Use the decimal module:

    from decimal import Decimal
    a = Decimal('1E-8')
    b = 10
    c = Decimal('1E-8')
    x1 = ((-b)-((b**2)-(4*a*c)).sqrt())/(2*a)
    x2 = ((-b)+((b**2)-(4*a*c)).sqrt())/(2*a)
    print 'x1 = {}'.format(x1)
    print 'x2 = {}'.format(x2)
    

    results in

    x1 = -999999999.999999999000000000
    x2 = -1.0000000000E-9