Home > Blockchain >  'ImmutableDenseNDimArray' - Can't get equation to plot
'ImmutableDenseNDimArray' - Can't get equation to plot

Time:05-12

I'm trying to plot an equation, but I can't seem to do it because of the error mentioned above.

This is a snippet of the code, should work by itself:

import numpy as np
from numpy import linspace
from sympy import *
import matplotlib.pyplot as plt

x , t = symbols('x t')

test = simplify(-(0.02631027*sin(3*x) 0.1594*cos(3*x))*exp(-1*x))
test_f = lambdify([x], test, modules="sympy")

# Creating vectors X and Y
x_num = np.linspace(0, 8, 10)

# Plot size
fig = plt.figure(figsize = (16, 7))

# Create the plot
plt.plot(x_num, test_f(x_num))  ← Error at this line!

plt.grid(alpha=.4,linestyle='--')
plt.legend()
plt.show()

At the line mentioned above, I get that error.

What should I do differently?

CodePudding user response:

You are mixing numpy with sympy, and that is what is causing the issue.

Let's analyze the code. Here you create a symbolic expression:

test = simplify(-(0.02631027*sin(3*x) 0.1594*cos(3*x))*exp(-1*x))

Here you are creating a lambda function asking it to be evaluated by sympy. This means the function will accept symbolic values and returns symbolic values:

test_f = lambdify([x], test, modules="sympy")

Then you create a Numpy array and pass it to the function, but it will raise the error you mentioned. That's because the function is expecting symbolic values, or values that can be converted to symbolic values. Turns out that a Numpy array cannot be converted to any symbolic value!

x_num = np.linspace(0, 8, 10)
test_f(x_num) # ERROR

What you need to do is to create a lambda function asking it to be evaluated by Numpy, like this:

test_f = lambdify([x], test)

The full correct code:

x , t = symbols('x t')

test = simplify(-(0.02631027*sin(3*x) 0.1594*cos(3*x))*exp(-1*x))
test_f = lambdify([x], test)

# Creating vectors X and Y
x_num = np.linspace(0, 8, 10)

# Plot size
fig = plt.figure(figsize = (16, 7))

# Create the plot
plt.plot(x_num, test_f(x_num))

plt.grid(alpha=.4,linestyle='--')
plt.legend()
plt.show()

CodePudding user response:

Your test_f produces:

In [113]: test_f(1)
Out[113]: 
                                      -1
(-0.02631027⋅sin(3) - 0.1594⋅cos(3))⋅ℯ  

In [114]: test_f(y)
Out[114]: 
                                          -y
(-0.02631027⋅sin(3⋅y) - 0.1594⋅cos(3⋅y))⋅ℯ  

In other words, it just a way of generating a sympy expression.

  • Related