Question: Please code in Python. I have completed the code but I need to add the method below and I am really confused: A method named
Please code in Python. I have completed the code but I need to add the method below and I am really confused:
A method named npolyVal(n, x) that takes two inputs: an integer n and a real number x. This method returns an approximation of the value of y at x, like the previous two methods. However, in this case, regression (best fitting) is used instead of interpolation. In the case of interpolation, the interpolating polynomial (linear or quadratic in the above two cases) passes exactly through the data points. In the case of regression, the goal is instead to find a polynomial that minimizes the square of the error (difference) between the data and the fitted polynomial. The idea is to generalize the familiar notion of a best fit line, to be a best fit polynomial. The parameter n determines the degree of the polynomial. If n is 1, the best fit is for a line, if n is 2, the best fit is quadratic etc. You should use the polyfit function from numpy to find the best fit polynomial. You should then evaluate the resulting polynomial at x and return this value.
Code below:
import numpy from SeqT import * class CurveT: def __init__(self,s): self.__s=s self.__x= SeqT() self.__y= SeqT() filename= open(self.__s, "r") i=0 for line in filename: currentline = line.split(",") x.add(i,currentline[0]) y.add(i,currentline[1]) i=i+1 return x return y
def linVal(self,x): for i in range(self.__x.sizeOf()): if (self.__x.get(i)==x): j= self.__x.indexInSeq(x) tempy2=self.__y.get(j+1) tempy1=self.__y.get(j-1) tempx1=self.__x.get(j-1) tempx2=self.__x.get(j+1) y=((tempy2-tempy1)/(tempx2-tempx1))*(x-tempx2) + tempy1 return y
def quadVal(self,x): for i in range(self.__x.sizeOf()): if(self.__x.get(i)==x): m=self.__x.indexInSeq(x) tempy2=self.__y.get(j+1) tempy1=self.__y.get(j-1) tempy0=self.__y.get(j-2) tempx0=self.__x.get(j-2) tempx1=self.__x.get(j-1) tempx2=self.__x.get(j+1) tempy=(((tempy2-(2*tempy1)+tempy0)/(2*((tempx2-tempx1)**2)))*((x-tempx1)**2) tempyy=((tempy2-tempy0)/(tempx2-tempx0))*(x-tempx1) y=tempy1+tempy+tempyy
return y def npolyVal(n,x):
// what would i need to do here
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
