Python Forum

Full Version: Mathematical function input
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is the best way to input a mathematical function (for example 5x^3+2x-5) in python? Also, can I somehow get a random number of polynoms? (for example up to x^5 or x^6) without defining the numbers of them inbefore?
Thanks for all help in advance,
Till
The best way to do a mathematical function with variables would be to use a string, otherwise, Python will give you a syntax error. As far as I know, Python does not work with Polynomials. There could however be a library. You could also make your own.
numpy can do polynomials: https://docs.scipy.org/doc/numpy/referen...mpy.poly1d

Your example, 5x^3+2x-5, would look like this:
>>> import numpy
>>> eq = numpy.poly1d([5, 0, 2, -5])
>>> print(eq)
   3
5 x + 2 x - 5
>>> for i in range(5):
...   print(f"x={i}: {eq(i)}")
...
x=0: -5
x=1: 2
x=2: 39
x=3: 136
x=4: 323
It'll work with any length of polynomial (so yes, x^5 or x^6), since it's based on the length of the list you pass it.