I tried various searches but couldn't find a good google string to bring up the right results.
I have a product of the form
y = x*f(x)
where f is a function of x which is not known. I want sympy to differentiate y with respect to x. Does anyone know how I can do this?
How about:
>>> x = sympy.Symbol("x")
>>> f = sympy.Function("f")
>>> y = x * f(x)
>>> y
x*f(x)
>>> y.diff(x)
x*Derivative(f(x), x) + f(x)
Related
This Sympy code works as I expect:
>>> x = sp.Symbol("x")
>>> y = sp.Symbol("y")
>>> z = sp.Symbol("z")
>>> (x+y+z).evalf(subs={"x":1, "y":2, "z":3})
6.0
However, if I use real-valued Symbols instead, the expression isn't simplified:
>>> x = sp.Symbol("x", real=True)
>>> y = sp.Symbol("y", real=True)
>>> z = sp.Symbol("z", real=True)
>>> (x+y+z).evalf(subs={"x":1, "y":2, "z":3})
x + y + z
I was unable to find an explanation for this by searching with keywords like sympy symbol real evalf - I only get unrelated results.
Why isn't the expression simplified in the second case? How can I substitute in values for real-valued Symbols and evaluate the expression?
Use the symbols as keys for the dictionary of substitutions, rather than string names:
>>> (x + y + z).evalf(subs={x: 1, y: 2, z: 3})
6.00000000000000
There appears to be an inconsistency between how complex and real symbols are treated:
>>> x = sp.Symbol('x')
>>> x.subs(x, 1)
1
>>> x.subs('x', 1)
1
>>> x = sp.Symbol('x', real=True)
>>> x.subs(x, 1)
1
>>> x.subs('x', 1)
x
I can't find anything relevant about this in the documentation, and the built-in help text isn't useful either. My best guess is that a string 'x' is naively converted using sp.Symbol, and the resulting symbol is always a complex-valued symbol that doesn't match the real-valued one with the same name.
I would consider this behaviour a bug and file a bug report (or look for an existing report). IMO, if a string is usable at all, it should match any symbol with that name; and an expression shouldn't be able to contain two different variables with the same name and different types; and trying to substitute in a variable with a matching name and incompatible type should probably raise an exception:
>>> x = sp.Symbol('x')
>>> # why allow this?
>>> broken = sp.Symbol('x', real=True) + x
>>> broken # if the types matched, it would simplify to 2*x
x + x
>>> # surely 2 is the only value that makes sense?
>>> broken.subs('x', 1)
x + 1
>>> x.subs('x', 1)
1
>>> # If this is allowed at all, surely the result should be 1?
>>> x.subs(sp.Symbol('x', real=True), 1)
x
Im trying to build a constrained optimization calculator in python using the sympy module. The idea is that a user can enter two functions, "f" and "g", which then are put together to form the equation "L".
I want SymPy to give me the partial derivatives of x, y and lambda in "L", however my code does not seem to be working. When trying to get their partial derivatives i get the following results:
0
0
-x - 4*y + 500
I used x+100*y-y**2 as function 1 and x+4*y-500 and function 2.
Heres the code so far:
import sympy as sp
from sympy.parsing import sympy_parser
x, y = sp.symbols("x y", real=True)
lam = sp.symbols('lambda', real=True)
insert = input("Insert function 1:") #function 1
f = sympy_parser.parse_expr(insert) #transforming the function into a sympy expression
print(f)
insert2 = input("Insert function 2:") #function2
g = sympy_parser.parse_expr(insert2) #transforming function 2
L = f - lam*g #getting the equation "L"
xx = sp.diff(L, x) #partial derivative L'x
yy = sp.diff(L, y) #partial derivative L'y
ll = sp.diff(L, lam) #partial derivative L'lam
print(xx)
print(yy)
print(ll)
I have tried both the "parse_expr" and "simpify" commands to transform the functions input by the user from string to sympy expressions. I might be missing something else.
Your local x and y are real but those that the parser returns are vanilla, they have not assumptions. Since symbols match by name and assumptions, your input functions don't have (the same) x and y:
>>> f.has(x)
False
So either don't make your local symbols real
>>> var('x')
x
>>> f = sympy_parser.parse_expr(insert)
>>> f.has(x)
True
Or pass your local symbols to the parser so it can use them to build your functions:
>>> f = sympy_parser.parse_expr(insert, dict(x=x,y=y))
>>> f.has(x)
True
And once you are using the same symbols, the rest of your issues should move to a new level :-)
In Charm Crypto, how would I go about getting at the multiplicative inverse for ZR? I have roughly the following code:
a = group.random(G)
e = group.random(ZR)
x = a ** e
somestuff()
y = x ** (1/e)
where a is not stored on purpose. However while -e works fine to get the additive inverse there doesn't seem to be a proper way to get at the multiplicative inverse.
Not sure what you mean. 1/e is the proper modular inverse in Charm Crypto. Here is a full example:
>>> from charm.toolbox.pairinggroup import PairingGroup,ZR,G1,G2,GT,pair
>>> group = PairingGroup('SS512')
>>> a = group.random(G1)
>>> a
[2580989876233721415297389560556166670922761116088625446257120303747454767083854114997254567159052287206977413471899062293779511058710074633103823400659019, 5996565379972917992663126989138580820515927146496218666993731728783513412956887506732385903379922348877197471677004946545491932261438787373567446770237791]
>>> e = group.random(ZR)
>>> x = a ** e
>>> x
[6891729780372399189041525470592995101919015470165150216677136432042436097937961533731911650601678002293909918119625724503886943879739773465990776556262311, 1548281541526614042816533932120191809063134798488215929407179466331621937371141709171095414449680510602430538669648224266688052566354236898986673964076468]
>>> y = x ** (1/e)
>>> y
[2580989876233721415297389560556166670922761116088625446257120303747454767083854114997254567159052287206977413471899062293779511058710074633103823400659019, 5996565379972917992663126989138580820515927146496218666993731728783513412956887506732385903379922348877197471677004946545491932261438787373567446770237791]
>>> y == a
True
Perhaps somestuff() changes x or e in some way that it doesn't work.
I have a number of symbolic expressions in sympy, and I may come to realize that one of the coefficients is zero. I would think, perhaps because I am used to mathematica, that the following makes sense:
from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
f = x + y
x = 0
f
Surprisingly, what is returned is x + y. Is there any way, aside from explicitly calling "subs" on every equation, for f to return just y?
I think subs is the only way to do this. It looks like a sympy expression is something unto itself. It does not reference the pieces that made it up. That is f only has the expression x+y, but doesn't know it has any link back to the python objects x and y. Consider the code below:
from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
f1 = x + y
f2 = z + f1
f1 = f1.subs(x,0)
print(f1)
print(f2)
The output from this is
y
x + y + z
So even though f1 has changed f2 hasn't. To my knowledge subs is the only way to get done what you want.
I don't think there is a way to do that automatically (or at least no without modifying SymPy).
The following question from SymPy's FAQ explains why:
Why doesn't changing one variable change another that depends it?
The short answer is "because it doesn't depend on it." :-) Even though
you are working with equations, you are still working with Python
objects. The equations you are typing use the values present at the
time of creation to "fill in" values, just like regular python
definitions. They are not altered by changes made afterwards. Consider
the following:
>>> a = Symbol('a') # create an object with name 'a' for variable a to point to
>>> b = a + 1; b # create another object that refers to what 'a' refers to
a + 1
>>> a = 4; a # a now points to the literal integer 4, not Symbol('a')
4
>>> b # but b is still pointing at Symbol('a')
a + 1
Changing quantity a does not change b; you are not working with a set
of simultaneous equations. It might be helpful to remember that the
string that gets printed when you print a variable refering to a sympy
object is the string that was give to it when it was created; that
string does not have to be the same as the variable that you assign it
to:
>>> r, t, d = symbols('rate time short_life')
>>> d = r*t; d
rate*time
>>> r=80; t=2; d # we haven't changed d, only r and t
rate*time
>>> d=r*t; d # now d is using the current values of r and t
160
Maybe this is not what you're looking for (as it was already explained by others), but this is my solution to substitute several values at once.
def GlobalSubs(exprNames, varNames, values=[]):
if ( len(values) == 0 ): # Get the values from the
for varName in varNames: # variables when not defined
values.append( eval(varName) ) # as argument.
# End for.
# End if.
for exprName in exprNames: # Create a temp copy
expr = eval(exprName) # of each expression
for i in range(len(varNames)): # and substitute
expr = expr.subs(varNames[i], values[i]) # each variable.
# End for.
yield expr # Return each expression.
# End for.
It works even for matrices!
>>> x, y, h, k = symbols('x, y, h, k')
>>> A = Matrix([[ x, -h],
... [ h, x]])
>>> B = Matrix([[ y, k],
... [-k, y]])
>>> x = 2; y = 4; h = 1; k = 3
>>> A, B = GlobalSubs(['A', 'B'], ['x', 'h', 'y', 'k'])
>>> A
Matrix([
[2, -1],
[1, 2]])
>>> B
Matrix([
[ 4, 3],
[-3, 4]])
But don't try to make a module with this. It won't work. This will only work when the expressions, the variables and the function are defined into the same file, so everything is global for the function and it can access them.
Given a simple equation such as:
x = y + z
You can get the third variable if you bind the other two (ie: y = x - z and z = x - y). A straightforward way to put this in code:
def solve(args):
if 'x' not in args:
return args['y'] + args['z']
elif 'z' not in args:
return args['x'] - args['y']
elif 'y' not in args:
return args['x'] - args['z']
else:
raise SomeError
I obviously can take an equation, parse it and simplify it to achieve the same effect.
But I believe in doing so I would be re-inventing the wheel. So where's my ready-made wheel?
Consider using Sympy. It includes various tools to solve equations and a lot more.
The following is an excerpt from the docs:
>>> from sympy import I, solve
>>> from sympy.abc import x, y
>>> solve(x**4-1, x)
[1, -1, -I, I]