Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

numerical - How use creating polynomial expression like function in Python?

I'd like to write a program in Python where user define a deegre of polynomial and coefficients (a,b,c). When program create a polynomial expression with this data I'd like to use it like function because I need this to other operations. How can i get it? For example when I have polynomial= x^n+a^n-1+b^n-2+c^-3 I'd like to use it in polynomial(x) to calculate value.

Now the creating polynomial method looks:

def polynomial(n,a,b,c):
    return a*x**n+b*x**3-c*x
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
class Polynomial:

    def __init__(self, coeficents, degrees=None):
        if degrees = None:
            self.degree = list(reversed(range(len(coeficents))))
        else:
            self.degree = degrees
        self.coeficents = coeficents

    def __call__(self, x):
        print(self.coeficents)
        print(self.degree)
        return sum([self.coeficents[i]*x**self.degree[i] for i in range(len(self.coeficents))])



p = Polynomial([1,2,4],[10,2,0])
print(p(2))

This will compute the polynomial x^10 + 2x^2 + 4 at x = 2. It should be very clear how to use with your example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...