Last active
December 22, 2015 13:08
-
-
Save Bolt64/6476781 to your computer and use it in GitHub Desktop.
A small script to interpolate data points and return a polynomial going through those points.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
README | |
To use this script you must have python and numpy installed. | |
Just download the script, open up the terminal and execute the | |
script as './interpolate.py -i' for the interactive mode | |
and './interpolate -f file' to use a file as the data source. | |
the file must be formatted as input/output pairs separated by a comma. | |
The script will print a list as output. The first number is the constant, | |
the second is the coefficient of x, the third of x^2 and so on. | |
For any more info, contact Sayantan Khan at bolt.khan@gmail.com | |
''' | |
import numpy as np | |
class InvalidDataError(Exception): | |
pass | |
def interpolator(data_points): | |
poly_degree=len(data_points)-1 | |
number_of_variables=len(data_points) | |
main_array=np.array([[i[0]**j for j in range(0,poly_degree+1)]+[i[1]] for i in data_points]) | |
primary_array=main_array[:,:-1] | |
primary_array_det=np.linalg.det(primary_array) | |
if primary_array_det!=0: | |
variables=[] | |
for i in range(number_of_variables): | |
temp_det=np.linalg.det(np.delete(main_array,i,1))*(-1)**(number_of_variables-(i+1)) | |
varial=temp_det/primary_array_det | |
variables.append(varial) | |
return variables | |
else: | |
raise InvalidDataError() | |
def file_parser(file_object): | |
content=file_object.readlines() | |
return_list=[[float(j) for j in i.strip().split(',')] for i in content] | |
return return_list | |
def diff_poly(coeff_list,number_of_times=1): | |
print('i') | |
if number_of_times!=0: | |
if coeff_list!=[0]: | |
for i in range(len(coeff_list)): | |
coeff_list[i]=coeff_list[i]*i | |
coeff_list.pop(0) | |
elif coeff_list==[0]: | |
pass | |
return diff_poly(coeff_list,number_of_times-1) | |
elif number_of_times==0: | |
return coeff_list | |
if __name__=='__main__': | |
from sys import argv | |
if argv[1]=='-i': | |
input_val=[] | |
print("Enter the input/output pair as comma separated values.") | |
while True: | |
inputs=raw_input() | |
if inputs!='': | |
input_val.append([int(i) for i in inputs.split(',')]) | |
elif inputs=='': | |
break | |
print(interpolator(input_val)) | |
elif argv[1]=='-f': | |
file_obj=open(argv[2]) | |
print(interpolator(file_parser(file_obj))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment