Forum Archive

Sympy solve() rounds to 0?

donnieh

I am passing solve() big and small numbers such as electron_charge = 1.6e-19

The function rounds those small numbers to 0. Has anyone seen this? An example is below.

from sympy import *
x, y, z = symbols('x y z')

# this works because its only 1e-5
rslt = solve(Eq(0+1e-5, x), x)
rslt = rslt[0]
print rslt

#this outputs zero cause number is too small? :(
rslt = solve(Eq(0+1e-10, x), x)
rslt = rslt[0]
print rslt
JonB

you will want the rational=False flag for solve. otherwise it tries to find approximate rational expressions.

dgelessus

Try adding the flag rational=False to the solve call:

solve(Eq(1e-10, x), x, rational=False)

By default, sympy converts floats to rationals and apparently this causes precision issues (even though when I do Float(Rational(1e-10)) by hand I see no precision loss, but whatever).

@omz According to this discussion on Stack Overflow something related to this has been fixed in sympy 0.7.5, and Pythonista comes with 0.7.4.1. Might be worth updating if you haven't done so already internally.

donnieh

Oh ok! Thanks guys! Very helpful.