I want to calculate a polynomial on x value. I tried to write
a function that takes as argument an array of integer and integer x
the function will returns the value of the polynomial in x.
def pol(L, x):
P = None
for i in L:
P = L[0] * (x ** 0) + L[1] * (x ** 1) + L[2] * (x ** 2)
return P
L = [0, 2, 4]
x = 3
print(pol(L, x))
I also tried
def pol(L, x):
P = None
for i in L:
j = 0
P = sum(i * (x ** j))
j += 0
return P
L = [0, 2, 4]
x = 3
print(pol(L, x))
It will return 42 for this example.
I don't know how to increment.
Thanks
Building up on your attempts, one straightforward way to get the polynomial would be the following:
def poly(p, x):
val = 0
for i, pp in enumerate(p):
val += pp * x**i
return val
There are faster and more elegant ways to do this, though. I'd strongly encourage you to use numpy.polyval() for efficiency.
Note that for the numpy implementation, p[0] is the highest order polynomial while for the example shown here, p[0] is the lowest order!
p = [0, 2, 4]
x = 3
poly(p, x)
>> 42
import numpy as np
poly(p, x) == np.polyval(p[::-1], x)
>> True
Related
I have to find the number of solution depending on the parameter a. While solving the equation numerically using scipy.optimize.root I get some numbers which aren't root of the function. For example for
x = 7*sin(x) i get numbers -7.71046524 and 7.71046524. My code is:
a = np.linspace(-5, 5)
def fun(x):
return x - b*np.sin(x)
for i in a:
solutions = []
b = i
c = abs(int(round(i)))
for j in range(-c, c+1):
y = root(fun, j)
if (round(y.x[0], 3) not in solutions):
solutions.append(round(y.x[0], 3))
print(len(solutions))
If you use scipy.optimize.root, the return value contains x the solution array and the success boolean flag. You need to filter out any result where success is False.
import numpy as np
from scipy.optimize import root
a = np.linspace(-7, 7)
def fun(x):
return x - b*np.sin(x)
for i in a:
solutions = []
b = i
c = abs(int(round(i)))
for j in range(-c, c+1):
y = root(fun, j)
if y.success and (round(y.x[0], 6) not in solutions):
solutions.append(round(y.x[0], 3))
print(i, solutions)
I am trying to solve the following question. I have made codes for implanting the direct method and Horner's rule, which I believe I have done this correctly. However past that I am having some problems figuring out the rest. Looking for some help with this, all help is greatly appreciated!
Here is the code I have produced for Horner's rule, which I believe I have done correctly.
def poly_horner(A, x):
p = A[-1]
i = len(A) - 2
while i >= 0:
p = p * x + A[i]
i -= 1
return p
And here is the code I have produced for the direct method:
def poly_naive(A, x):
p = 0
for i, a in enumerate(A):
p += (x ** i) * a
return p
How can I put this code together and finish the rest?
Using global as suggested in the paper,
flops = 0
def add(x1, x2):
global flops
flops += 1
return x1 + x2
def multiply(x1, x2):
global flops
flops += 1
return x1 * x2
def poly_horner(A, x):
global flops
flops = 0
p = A[-1]
i = len(A) - 2
while i >= 0:
p = add(multiply(p, x), A[i])
i -= 1
return p
def poly_naive(A, x):
global flops
flops = 0
p = 0
for i, a in enumerate(A):
xp = a
for _ in range(i):
xp = multiply(xp, x)
p = add(p, xp)
return p
To run the above code, for example:
>>> poly_horner([1,2,3,4,5], 2)
129
>>> print(flops)
8
Compare to numpy's polyval:
>>> import numpy as np
>>> np.polyval([5,4,3,2,1], 2)
129
I know there is generator yield in python like:
def f(n):
x = n
while True:
yield x
x = x+1
So I try to convert this haskell function into python without using iterate: Haskell infinite recursion in list comprehension
I'm not sure how to define base case in python, also not sure how to combine if statement with this yield staff! here is what I try to do:
def orbit(x,y):
while True:
yield p (u,v)
p (u,v) = (u^2 - v^2 + x, 2 * u * v + y)
I dont see where you're getting the p from. As far as I can see you can almost literally translate it from Haskell:
def orbit(x, y):
u, v = 0, 0
while True:
u, v = u**2 − v**2 + x, 2*u*v + y
yield u, v
In their example, calling the function as orbit(1, 2), u will be bound to 1 and v to 2 in the first round, then that ((1, 2)) is yielded. In the next iteration, u = 1**2 - 2**2 + 1 = 1 - 4 + 1 = -2 and v = 2*1*2 + 2 = 6.
I've written out a couple of functions for doing expmod, that is, (x ** y) % n. These are both standard functions, I've checked and re-checked both but can't find any silly errors.
Here's the recursive one:
def expmod(x,y,m):
if y == 0: return 1
if y % 2 == 0:
return square(expmod(x,y/2,m)) % m # def square(x): return x*x
else:
return (x * expmod(x,y-1,m)) % m
...and here's the non-recursive one:
def non_recursive_expmod(x,y,m):
x = x % m
y = y % m
result = 1
while y > 0:
if(y%2 == 1):
result = (result * x) % m
x = (x*x) % m
y = y/2
return result
They agree for small values:
>>> expmod(123,456,789) - non_recursive_expmod(123,456,789)
0
...but don't for larger ones:
>>> expmod(24354321,5735275,654) - non_recursive_expmod(24354321,5735275,654)
-396L
What's going on?
Your function non_recursive_expmod has some suspicious steps in it: Remove the %m for x and y at the beginning. Both are not needed.
Additionally make sure that the division of y is an integer division by using y = y // 2.
In total the function should look like this:
def non_recursive_expmod(x, y, m):
result = 1
while y > 0:
if y % 2 == 1:
result = (result * x) % m
x = (x * x) % m
y = y // 2
return result
Non recursive does not decrease y in case it is odd, and even part needs else in case y == 1
I have been doing python programming for my project and I have just started. This might be another trivial question. I have this code in which I need to use a value calculated in the function poly_root() which is x. That value should be used as u in the bezier() function. After poly_root() function it should go to bezier() function with its calculated value. I dont know if I am doing it in the correct way. There is no error but it doesnt print t from the bezier() function. Thank you very much.
import copy
import math
poly = [[-0.8,3], [0.75,2], [-0.75,1], [0.1,0]]
def poly_diff(poly):
""" Differentiate a polynomial. """
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
""" Apply values to the polynomial. """
sum = 0.0 # force float
for term in poly:
sum += term[0] * (x ** term[1])
return sum
def poly_root(poly, start, n, r_i):
""" Returns a root of the polynomial, with a starting value."""
poly_d = poly_diff(poly)
x = start # starting guess value
counter = 0
while True:
if (n >= 0) and (n < 1):
break
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
if x_n == x:
break
x = x_n # this is the u value corresponding to the given time which will be used in bezier equation
n -= 1
counter += 1
if r_i:
#print [x, counter])
return [x, counter]
else:
#print x
return x
bezier(x)
def bezier(value) :
""" Calculates control points using rational bezier curve equation"""
u = value
w = 5
t = math.pow(1-u,3) * points[0][0] + 3 * u * math.pow(1-u,2) * points[1][0] \
+ 3 * (1-u) * math.pow(u,2) * points[2][0] + math.pow(u,3) * points[3][0]
t = t * w
d = math.pow(1-u,3) * w + 3 * u * w * math.pow(1-u,2) + 3 * (1-u) * w \
* math.pow(u,2) + math.pow(u,3) * w
t = t / d
print t
if __name__ == "__main__" :
poly_root(poly, 0.42, 1, 0)
In this part of code:
if r_i:
#print [x, counter])
return [x, counter]
else:
#print x
return x
bezier(x)
bezier(x) is unreachable. You need to rewrite it.
It would be better for poly_root to return the same type of thing in both situations (i.e. a list with two elements) ...
if r_i:
return [x, counter]
else:
return [x, None]
Then at the bottom, you can have ...
if __name__ == "__main__" :
x, counter = poly_root(poly, 0.42, 1, 0)
if counter is None: # I don't know if this is what you intended with your code.
bezier(x)