Turbinenreiter
Turbinenreiter

Reputation: 57

Sympy refuses to calculate values

I'm trying to implement a markdown-like language to do math with. The basic idea is to have a file where you can write down your math, then have a python-script do the calculations and spit out tex.

However, I'm facing the problem, that Sympy refuses to spit out values, it only gives me back the equation. Much weirder is the fact, that it DOES spit out values in an alternate test-script, that is essentially the same code.

This is the working code:

import sympy as sp
m = sp.symbols('m')
kg = sp.symbols('kg')
s = sp.symbols('s')
g = sp.sympify(9.80665*m/s**2)
mass = sp.sympify(0.2*kg)
acc = sp.sympify(g)
F = sp.sympify(mass*acc)
print F

Output:

1.96133*kg*m/s**2

This the not working code:

import re
import sympy as sp
print 'import sympy as sp'

#read units
mymunits = 'units.mymu'
with open(mymunits) as mymu:
    mymuinput = mymu.readlines()
    for lines in mymuinput:
        lines = re.sub('\s+','',lines).split()
        if lines != []:
            if lines[0][0] != '#':
                unit = lines[0].split('#')[0]
                globals()[unit] = sp.symbols(unit)
                print unit+' = sp.symbols(\''+unit+'\')'

#read constants
mymconstants = 'constants.mymc'
with open(mymconstants) as mymc:
    mymcinput = mymc.readlines()
    for lines in mymcinput:
        lines = re.sub('\s+','',lines).split()
        if lines != []:
            if lines[0][0] != '#':
                constant = lines[0].split('#')[0].split(':=')
                globals()[constant[0]] = sp.sympify(constant[1])
                print constant[0]+' = sp.sympify('+constant[1]+')'

#read file
mymfile = 'test.mym'
with open(mymfile) as mym:
    myminput = mym.readlines()
    #create equations by removing spaces and splitting lines
    for line in myminput:
        line = line.replace(' ','').strip().split(';')
        for eqstr in line:
            if eqstr != '':
                eq = re.split(':=',eqstr)
                globals()[eq[0]] = sp.sympify(eq[1])
                print eq[0]+' = sp.sympify('+eq[1]+')'

print 'print F'
print F

It outputs this:

acc*mass

It SHOULD output a value, just like the test-script. The same script also outputs the code that is used in the test-script. The only difference is, that in the not-working script, I try to generate the code from an input-file, which looks like that:

mass := 0.2*kg ; acc := g

F := mass*acc

as well as files for units:

#SI

m       #length
kg      #mass
s       #time

and constants:

#constants

g:=9.80665*m/s**2       #standard gravity

The whole code is also to be found on github. What I don't get is why the one version works, while the other doesn't. Any ideas are welcomed. Thank you.

Upvotes: 1

Views: 405

Answers (1)

Turbinenreiter
Turbinenreiter

Reputation: 57

Based on Everts comment, I cam up with this solution:

change:

sp.sympify(eq[1])

to:

sp.sympify(eval(eq[1]))

Upvotes: 1

Related Questions