Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mathematical function input
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,
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:

Your example, 5x^3+2x-5, would look like this:
>>> import numpy
>>> eq = numpy.poly1d([5, 0, 2, -5])
>>> print(eq)
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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  Function with array input Gerkamspiano 5 195 Dec-01-2020, 08:48 AM
Last Post: Gerkamspiano
  calling a function and argument in an input phillup7 3 280 Oct-25-2020, 02:12 PM
Last Post: jefsummers
  About mathematical equations seyidcemkarakas 3 252 Oct-04-2020, 01:21 PM
Last Post: Gribouillis
  Recognising mathematical expressions from word and pdf file Preeti15 0 282 Aug-19-2020, 09:06 AM
Last Post: Preeti15
  Use of input function to change screen background color in Turtles Oldman45 3 655 Jul-10-2020, 09:54 AM
Last Post: Oldman45
  Mathematical Conversion Scripts for Weather Station Mickey53usa 11 1,039 Jun-24-2020, 03:14 AM
Last Post: buran
  Getting an error while using input function dcsethia 5 489 May-11-2020, 04:59 PM
Last Post: buran
  Mathematical Operators in String AgileAVS 1 530 Mar-04-2020, 04:14 PM
Last Post: Gribouillis
  Input() function not working in VS Code darpInd 7 960 Feb-17-2020, 03:28 PM
Last Post: snippsat
  Using input function in a Class wew044 2 543 Feb-06-2020, 03:08 AM
Last Post: wew044

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020