Search code examples
pythonsubstitutionsymbolic-math

How to Insert an Array of Values to a Symbolic Function in Python


I want to study symbolic functions in python. I want to create y(x) = x^2 + 2x + 3 and plot it in the range [1, 255]. I want to use the subs() function to calculate the values by using the for loop. However, when I run that I get this error:

IndexError('list index out of range')

Can you help me please?

import numpy as np
import matplotlib.pyplot as plot
from sympy import *

a = [1,2,3]

x = Symbol('x')
fx = a[0]*x**2 + a[1]*x + a[2]

t = list(range(1,256))
y = np.zeros(256)

for i in t:
    y[i] = fx.subs({x:t[i]})

plot.plot(t,y)
plot.show()

Solution

  • Just replace with the following lines:

    y = np.zeros(len(t))
    
    for i in range(len(t)):
        y[i] = fx.subs({x:t[i]})
    

    The problem was that the length of t was only 255 but the len of y was 256 in your code because you define y = np.zeros(256), hence the Index Error because there is no t[256]. I am using y = np.zeros(len(t)) because you have as many y points as t (or x) points. By the way, you are most likely to get an error in your plot command the way it is right now because you have called import matplotlib.pyplot as plot. I would simply call it plt instead of plot

    Output

    enter image description here