Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting with SymPy

Tags:

python

sympy

With SymPy, I can plot a function with:

f, a = symbols('f a')
f = a + 10
plot(f)

However, if I define the function as:

f, a, b = symbols('f a b')
f = a + b
b = 10
plot(f)

Then I get an error stating:

ValueError: The same variable should be used in all univariate
            expressions being plotted.

How can I plot f if I define f = a + b, considering that b is assigned a constant value before plotting the function?

like image 941
Peque Avatar asked Apr 17 '16 16:04

Peque


People also ask

How can I substitute SymPy?

The subs() function in SymPy replaces all occurrences of the first parameter with the second. Substitution is the basic operations that must be performed in a mathematical expression. In this way, we can use subs() function in sympy.

How do you evaluate a SymPy expression?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .


2 Answers

The lines

f, a, b = symbols('f a b')
f = a + b
b = 10

don't change b in the expression. If you print f you'll see that it is still defined as a + b.

You are confusing Python variables with SymPy symbols. In the first line, the Python variable b points to a SymPy symbol named b (in fact, they need not be the same name; you could have also written x = Symbol('b') and y = a + x). In the second line, the variable f points to a SymPy expression containing the symbol b. In the third line, the variable b points to the integer 10. This doesn't not change any previous lines that used the variable b, since they have already been run. It's no different than if you ran

a = 1
b = 1
c = a + b
b = 2

You would expect the value of c at the end to be 2, not 3. Similarly, when b points to a Symbol, expressions you create with it use a Symbol, but if you change it to point to a number, it doesn't affect previous lines from when it was a Symbol.

The recommended way to deal with this in SymPy is to avoid assigning the same variable to a symbol and then later to a non-symbol (it's worth pointing out that your definition of f in the first line is completely useless, since you immediately redefine it in the second line). To replace a symbol in an expression, use subs:

a, b = symbols('a b')
f = a + b
f1 = f.subs(b, 10)

Note that subs does not change the original f. It returns a new expression.

This document may also help clear this confusion up.

like image 188
asmeurer Avatar answered Sep 18 '22 10:09

asmeurer


If you didn't want to use substitution as in the other answer, you could make f an actual function of course

def f(a, b):
    return a + b
a = symbols('a')
b = 10
plot(f(a,b))
like image 24
miradulo Avatar answered Sep 19 '22 10:09

miradulo