On Mon, Apr 23, 2012 at 10:41 AM, phneoix <[email protected]> wrote:
> hi,
> i have been using spreadsheet for modelling of mathematical
> problems. is it possible to use sympy for the same.
> eg.
>
> T=f*d
>
> T=100
> f=?
> d=10
> .
>
>
> i can use goalseek function in spreadsheet to find the value of 'f'.
> can i use sympy for the same sort of problems without having to
> transpose the equation.
>
Yes, with a couple of caveats:
1) you have to remember that if you define something then it's no
longer a symbol that you can solve for:
>>> from sympy.abc import x, y
>>> x = 2
>>> Eq(y, x)
y == 2
2) You can't enter equations like above, but should use the Eq()
function to set up equalities. So for your question it might look like
this:
>>> T=100
>>> d=10
>>> solve(Eq(T, f*d), f)
[10]
3) If you want to solve for a variety of variables using the same
equation then an idiom like this might work:
>>> var('f T d') # another way to make (or re-make) the variables
(f, T, d)
>>> eq = Eq(T , f*d)
>>> eq
T == d*f
>>> solve(eq.subs(dict(T=100,d=10)))
[10]
Let's look at that a step at a time.
dict() creates a dictionary of the items given. Note that the keys are strings.
>>> dict(T=100,d=10)
{'d': 10, 'T': 100}
This hasn't assigned a value to T or d in your workspace. When you feed
this dictionary to subs, however, it converts the strings to sympy expressions
which, in this case, are symbols and then does the replacement in you
symbolic equation:
>>> eq.subs(dict(T=100,d=10))
100 == 10*f
Solve then, if you don't tell it what to solve for just solves for a
missing symbol
since there is only one in this case, the solution you got was for f
>>> solve(_)
[10]
sympy is a library that provides tools to help you; python allows you to make
your own tools; since sympy is written in python the two work well together :-)
So if you wanted to have a tool that would take the input like you gave and just
tell you the answer it might look like this:
def ssolve(s, *v):
"""
Solve lines of equations as a set of equations:
>>> from sympy.my import ssolve
>>> ssolve('''
... y=x+3
... x+y=4''')
{x: 1/2, y: 7/2}
Any line containing an '?' will be ignored.
>>> ssolve('''
... y=x+3
... y=4
... x=?''')
{x: 1, y: 4}
"""
from sympy import Eq, solve, Tuple
eq=[]
for li in [si for si in s.strip().splitlines() if si]:
li.replace('==','=')
if '?' in li: continue
if '=' in li: eq.append(Eq(*[S(p) for p in li.split('=')]))
else: eq.append(S(li))
return solve(eq, *(v or list(Tuple(*eq).free_symbols)))
Hope that helps, and welcome to SymPy,
Chris
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.