Open source language/library/representation format that allows treating numeric formulas as objects?

StackOverflow https://stackoverflow.com/questions/7330284

Question

I'm looking for a way to store a series of formulas/equations as text (so they are easily diff-able). Later formulas depend on the results of earlier ones.

I should be able to evaluate the formulas (similar to Live Worksheets in MathCAD) to numeric results, but also be able to programmatically produce a string representation of the original formula.

Put another way, I'd like to be able to treat the formulas themselves as data, as well as evaluate the formulas.

I would like to have a text editor with syntax highlighting when editing the formulas.

My first approach was to have a Python file with the formulas stored as strings, then call eval() on the strings. However, this does not allow for syntax highlighting of the formulas.

My language of choice is Python, but I would be open to other non-proprietary solutions.

Example:

a = 73
b = 13
c = 100
d = 20
e = 18

x = a^2 + b / (c - min(d, e))
y = c + sqrt(x * e)

The intent is to automatically generate other code using the evaluated results of the formulas, while commenting that generated code with the original formulas themselves.

Was it helpful?

Solution

you can use sympy:

from sympy import *

a,b,c,d,e = symbols("a,b,c,d,e")
x = a**2 + b/(c-min(d,e))
y = c+sqrt(x*e)

values = {a:73,b:13,c:100,d:20,e:18}

print x
print y

print x.subs(values)
print y.subs(values)

print N(x.subs(values))
print N(y.subs(values))

the output is:

a**2 + b/(c - d)
c + (e*(a**2 + b/(c - d)))**(1/2)
426333/80
100 + 3*4263330**(1/2)/20
5329.16250000000
409.717492240913
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top