Python Forum
Mathematical function input - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Mathematical function input (/thread-20992.html)



Mathematical function input - Tiiill - Sep-09-2019

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


RE: Mathematical function input - SheeppOSU - Sep-09-2019

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.


RE: Mathematical function input - nilamo - Sep-10-2019

numpy can do polynomials: https://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html#numpy.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.