I am calculating (what seems to me) the same thing in two ways but am getting different results. I'd appreciate any help in understanding the reason behind this.
I have a list of symbolic equations, each defined as:
a1 * x1 + a2 * x2 + ... + a30 * x30 = b
eqs=[] # expressions
reps={} # values of symbols in the expressions
b=[] # numeric value that the known expression has
for i,e in enumerate(eqs):
A = (e-b[i]).subs(reps)
B = e.subs(reps)-b[i]
if A != B:
print (A, B)
These are giving different results for A and B:
The only reason these should be different is if you are substituting floating point values. And then the reason will likely be just the order in which SymPy process arguments. The best way to evaluate a symbolic expression with a dictionary of values is expr.evalf(subs=values)
, e.g. trivial case x.evalf(subs={x:1})->1.0
. Doing it this way will keep increasing precision to (try) make sure you get a meaningful and accurate result.
Experiments to try
apply nsimplify(v, rational=True)
to each float and compare the two methods. They should give the same results either way because Rational computations are exact (and slower) than those obtained from floats
in method one substitute in floats to compute the lhs and then do (lhs - b).evalf(subs={b: bval})
to see if you get the same thing as method tow with expr.evalf(subs=dict_of_all_values)
Data that would clearly demonstrate the issue is needed to make progress on this issue: just fill in the the details of the edited OP.