Reputation: 31
For my latest project in my coding class (python), we need to program and compute a cubic function. So something like 3x^3+2x^2+7x+1. I cannot figure out how to code in the different x powers. I know this is a very simple question, but I can't find what I am looking for on the internet and have searched. How would I write out this polynomial given the 3,2,7 & 1 values? I assume I need to use numpy but can only figure that out with a degree one polynomial.
Upvotes: 0
Views: 6098
Reputation: 46849
powers can be represented with **
in python (there is also a more sophisticated pow
) function:
def f(x):
return 3*x**3 + 2*x**2 + 7*x + 1
(in python ^
is the xor
operator; if you use your expression python would not complain but just not calculate what you want)
if you need to be able to do symbolic math, i suggest you install the sympy
package:
from sympy import symbols
def f(x):
return 3*x**3 + 2*x**2 + 7*x + 1
x = symbols('x')
print(f(x)) # 3*x**3 + 2*x**2 + 7*x + 1
print(f(x).subs(x, 5)) # 461
Upvotes: 2
Reputation: 9257
You can also create a custom function like this example:
def cubic(x, args):
args_len = len(args)
for k in args:
yield k * x ** (args_len-1)
args_len -=1
Demo:
user_input = [3, 2, 7, 1]
user_var_x = 1
somme = sum(cubic(user_var_x, user_input))
print(somme)
Output:
13
Upvotes: 0