Python Forum

Full Version: Polynomials
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to write a program that reads two numbers. Than used them in this polynomial: 3*x**3 - 5x + 0.8 and calculate all the values between them with a step of 0.5. I used range (value, value, 0.5). But only x will be defined, how do i define the other value? Any sugestions for a program like this?
Show the code that you have written so far so that suggestions can be made
#!/usr/bin/env python3
a = -5.0
b =  5.0

x = a
while x < b:
    print(x, 3*x**3 - 5*x + 0.8)
    x = x + 0.5
For numerical operations you should look for numpy.
There is a convenience function for polynomials.

numpy.poly1d
Quote:A convenience class, used to encapsulate "natural" operations on
polynomials so that said operations may take on their customary
form in code (see Examples).

Here a small example with your values:

import numpy as np
import matplotlib.pyplot as plt


x = np.linspace(-20, 20, 512) # from -20 to 20 (inclusive), 512 values
poly = np.poly1d([3, 0, -5, 0.8]) # your polynomial
y = poly(x)

plt.plot(x,y)
plt.show()
[attachment=289]
Good idea with mathplot