0% found this document useful (0 votes)
28 views13 pages

NC Assignment 2

Assignment Python based working for solving Numerical Computing problems like newton forward difference and interpolation etc.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
28 views13 pages

NC Assignment 2

Assignment Python based working for solving Numerical Computing problems like newton forward difference and interpolation etc.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
2610812024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony Practice to make a polynmial in numpy. import numpy as np x=[1,2,3] ‘np. poly1d(x) import numpy as np x=[1,2,3] # here 1,2,3 are coefficients of the polynomial in descending order Polysnp.poly1d(x) print(Poly1) Poly2=np.polyid(x,True) #another format to print polynomial print (Poly2) Code to read data from a CSV file import pandas as pd import numpy as np 4 Read data from CSV file df = pd.read_csv(‘data.csv') Convert data to numpy arrays x = éf["x values’ ].values y = df['y values" ].values Function for getting Lagrange Polynmial htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrco2OWS8prinMode=trus 1/13 2610372028, 18:13 224348 Saad Ahmed -Copy of Session_2 Interpolation ipynb - Colaboratory x = [0, 20,40,60, 80, 100] y = [26.0, -48.6, 61.6, -71.2, 74.8, -75.2] # Function to calculate Lagrange polynomial def lagrange_poly(x, y): n = len(x) P = np.poly1d(@.@) for i in range(n): L = np.polyid(y(i]) for j in range(n): ij lea: L = np.polyid( (1.0, -x(3]]) / (xi) - x{3]) paek return p # Calculate Lagrange polynomial p = lagrange_poly(x, y) print(p) 5 4 3 2 -5.329e-06 x + 0.001313 x - 0.1132 x + 3.985 x - 47.81 x + 26 For Interpolating at a specific point # Interpolate at a specific point point = float(input("Enter x-coordinate to interpolate: ")) interp_value = p(point) # Print Lagrange polynomial and interpolated value print(""Lagrange polynomial is:") print(p) print("Interpolated value at x » point, "isi", interp value) Enter x-coordinate to interpolate: 45 Lagrange polynomial is: 5 4 3 2 -5.329e-06 x + 0.001313 x - 0.1132 x + 3.985 x - 47.81 x + 26 Interpolated value at x = 45.0 is: 31.29079589843832 v TASK #01 Solve the above problem manually (Hand written & verify the polynomial & Interpolated value at x = 50 Show all the necessary steps and submitted in the form of PDF along with the project/.ipynb file at GCR Plotting of Lagrange Polynomial htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinModemrus 2/13 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony import matplotlib.pyplot as plt winds yi=31.29079589843832 p = lagrange_poly(x[@:6], y[0:6]) print(p) xpenp. Linspace(@,x[5], 100) yp=p(xp) plt.plot(xp, yp, label='Lagrange Poly’) plt.plot(xi, yi, ‘bo', label="Interpolated Point’) plt.plot(x[9:6], y[@:6], ‘ro’, label='Data Points’) plt.xlabel('x') plt.ylabel(*y') plt.legend() plt.show() 5 4 3 2 -5.329e-06 x + 0.001313 x - 0.1132 x + 3.985 x - 47.81 x + 26 — Lagrange Poly ae Interpolated Point © Data Points 100 0 > 0 50 100 150 fig = plt.figure(figsize = (10,8)) [@, 20,40,68, 80, 100] (26.0, -48.6, 61.6,-71.2, 74.8, -75.2] i in range(1,n42,1) Lagrange_poly(x[@:i+1], y[@:i+1]) xpenp. Linspace(@,x[i], 100) yp=p(xp) plt.plot(xp, yp, label = #*L{i}") plt.plot(x,y, ‘ro’ ,label="Data Points") plt.plot(xi,yi, 'bo' ,label="Interpolated Points") plt.xlabel('x') plt.ylabel(‘y') pit. legend() plt.grid() plt.show() htips:ilcola. research google.comidrvel 7GGWSUmFaHeMShUS9CbxGBINSTwAE2ro authuser=2AscrollTo=Wirgrsco2OWS8printMode=trus 33 2108/2024, 18:13 150 - Scipy Implimentation of Lagrange Polynomial 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony u QB eel] GB “ & Data Points Interpolated Points AY Instead we calculate everything from scratch, in scipy, we can use the lagrange function directly to interpolate the data. Let's see the above example htips:ilcola. research google.comidrvel 7GGWSUmFaHeMShUS9CbxGBINSTwAE2ro authuser=2AscrollTo=Wirgrsco2OWS8printMode=trus ans 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import lagrange # Define the data points X = np.array([@, 20, 48, 62, 86, 100]) y = np.array([26.0, -48.6, 61.6, -71.2, 74.8, -75.2]) # Define the Lagrange Polynomial = lagrange(x, y) # Find P(50) by evaluating the polynomial at x=50 pas = (45) print ("P(45) '» P45) # Plot the Lagrange Polynomial and the data points x_new = np.linspace(@, 102, 100) fig = plt.figure(figsize = (10,8)) plt.plot(x_new, f(x_new), 'b', x, y plt.plot(45, p_45, “go', markersize= plt.title(‘Lagrange Polynomial") plt.grid() plt.xlabel(‘x') plt.ylabel(*y') plt.show() P(45) = 31,29079589843832 Lagrange Polynomial 150 100 180 htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CbxGBINSTwAE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinModenrus 5/13 2108/2024, 18:13 1224945 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratory v Task # 02 Use the below code and apply the following alteration and show them along with plot (i) Take input from user and show interpolation at that point along with its plot. i) Also add a code that will display the polynomial too. Code for Newton divided difference Method import nunpy as np def divided _difference_table(x, y): n= len(x) F = [[0] * n for 4 in range(n)] for i in range(n): F(AI[@] = yli] for j in range(1, n): for i in range(j, n): FCAD(G] = (FLAN(G-2] ~ FLG-2](5-2]) / (xEa] - xfi-41) return F def newton_div_dif_poly(x,y,xi): livided_difference_table(x,y) # Saving divided difference in a variable F n=len(x) -poly1d(1) ip-poly1d(F[0][0]) for i in range(1,n): p-poly1d(x[:i], True) Ne=np.poly1d(FLi][i]*(prod.c)) print(N) print (N(Qxi)) return x = [0, 20,40,60, 80, 100] y = [26.0, -48.6, 61.6, -71.2, 74.8, -75.2] newton_div_dif_poly(x, y,45) 5 4 3 2 -5.329e-6 x + @.001313 x - @.1132 x + 3.985 x - 47.81 x + 26 31. 29079589843672 ¥ TASK 2 SOLUTION htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinMode=rus 6113 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratory import numpy as np import matplotlib.pyplot as plt def divided_difference_table(x, y): n= len(x) F = [[0] * n for i in range(n)] for i in range(n): F(i][@] = y[i] for j in range(1, n) for i in range(j, n): FEAJ(S] = (FLAN(5-2] - FEa-2)[5-2]) / (xi) - xfi-5)) return F def newton_div_dif_poly(x, y, xi): F = divided_difference_table(x, y) n= len(x) prod = np.polyld([1], True) N = np.poly1d(F[@][]) for i in range(1, n): prod *= np.polyld([1, -x[i-1]], True) N += F[i][i] * prod print(“Newton Divided Difference polynomial is:") print(N) print("Interpolated value at x =", xi, “is:", N(xi)) x_new = np.linspace(@, 100, 100) fig = plt.figure(figsize=(10, 8)) plt.plot(x_new, N(x_new), 'b', x, y, ‘ro') plt.plot(xi, N(xi), "go", markersize=10) plt.title( ‘Newton Divided Difference polynomial’) plt.grid() plt.xlabel(‘x') plt.ylabel('y') plt.show() point = float(input(“Enter x-coordinate to interpolate: “)) x= [@, 20, 40, 60, 80, 100] y = [26.0, -48.6, 61.6, -71.2, 74.8, -75.2] newton_div_dif_poly(x, y, point) htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinModentrus 7/13 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony Enter x-coordinate to interpolate: 5 Newton Divided Difference polynomial is uw 18 9 8 7 6 5.329e-06 x = 0.001034 x - 0.06804 x - 1.671 x - 7.838 x + 98.5 x 5 4 3 2 - 319 x + 515 x - 465.1 x + 228 x - 47.81 x + 26 Interpolated value at x = 5.0 is: -596987,7¢00000003 ael7 Newton Divided Difference polynomial 00} oe * * ° ° 05 10 a5 20 25 ° 20 0 60 80 100 v_ Task # 03 (A) Use the above code by adding divided difference table code i.e. it will show divided difference table. Task # 03 (B) htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrco2OWS8prinModentrus 813 2erorz02s 18:18 4228245 Saad Aimed - Copy of Sesion_2 Interpolation pnb Colaboratony With the help of "pandas" as shown at the starting of this lab session, read code from provided csv file & Write a code for Newton's forward divided difference. Print the polynomial and plot the interpolating point too. Task # 03 (C) Do part 3(8) manually (Mentioned all steps and verify the result. TASK 3 SOLUTION va) htips:ifcola. research google.comidrivel 7GGWSUmFaHeMShUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinModenrus SIN 2108/2024, 18:13 1224945 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratory import numpy as np import matplotlib.pyplot as plt def divided_difference_table(x, y): n= len(x) F = [[@] * n for i in range(n)] for i in range(n): F(i][@] = y[i] for j in range(1, n) for i in range(j, n): FEAJ(5] = CFLAN(5-2] - FEi-2)[5-2]) / (xi) - xfi-5)) return F def newton_div_dif_poly(x, y, xi): F = divided_difference_table(x, y) # Saving divided difference in a variable F n= len(x) prod = np.polyid(1) N = np.poly1d(F[@][]) for i in range(1, n): prod = np.polyid(x[@:i], True) N += np.poly1d(F[i][i]*(prod.c)) # Print Newton Divided Difference polynomial and interpolated value print ("Newton Divided Difference polynomial is:") print (N) print("Interpolated value at x =", xi, “is:", N(xi)) # Plot the Newton Divided Difference polynomial and the data points x_new = np.linspace(@, 100, 100) fig = plt.figure(figsize=(10, 8)) plt.plot(x_new, N(x_new), 'b’, x, y, ‘ro') plt.plot(xi, N(xi), ‘go’, markersize=10) plt.title( ‘Newton Divided Difference polynomial’) plt.grid() plt.xlabel('x") plt.ylabel(‘y") plt.show() return # Interpolate at a specific point point = float(input(“Enter x-coordinate to interpolate: ")) x = [@, 20, 40, 60, 80, 100] y = [26.@, -48.6, 61.6, -71.2, 74.8, -75.2] newton_div_dif_poly(x, y, point) htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTw4E2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinMode=trus 10/13 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony Enter x-coordinate to interpolate: 6 Newton Divided Difference polynomial is: 5 4 3 2 -5.329e-06 x + 0.001313 x - 0.1132 x + 3.985 x - 47.81 x + 26 Interpolated value at x = 6.0 is: -140.18998555e00002 Newton Divided Difference polynomial 100 150 » b) htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prinModemtrus 11/13 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratory import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from google.colab import files uploaded = files.upload() File_name = list(uploaded. keys())(0] df = pd.read_csv(file_name) df['x"] values y = df['y'].values def divided_difference_table(x, y): n = len(x) F = [[@] * n for 4 in range(n)] for i in range(n): FAIL] = yLi] for j in range(1, n): for i in range(j, n) PLACES] = (FES]EJ-2] - FE4-2) (5-2) return F def newton forward div dif_poly(x, y, xi): divided _difference_table(x, y) Jen(x) x1] - x[@] prod = np.poly1d(1) N = np.poly1d(F[@][0]) for i in range(1, n prod *= np.poly1d([1, (xi - x[i-1]) / h - 1], True) N += (F[A][i] / math.factorial(i)) * prod print ("Newton Forward Divided Difference polynomial is:") print(N) print ("Interpolated value at x xi, "isi", N(xi)) x_new = np.linspace(min(x), max(x), 100) fig = plt.figure(figsize=(10, 8)) plt.plot(x_new, N(x_new), 'b’, x, y, ‘ro') plt.plot(xi, N(xi), ‘go’, markersize=10) plt.title( ‘Newton Forward Divided Difference polynomial’ ) plt.grid() plt.xlabel('x") plt.ylabel('y") plt.show() return point = 55 newton_forward_div dif _poly(x, y, point) htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUS9CbxGBINSTwHE2ro7authuser=2HscrolTo=Wirgrtco2OWS8prin’Mode=trus 12/13 2108/2024, 18:13 1224345 Saad Ahmed - Copy of Session_2 Interpolation ipynb - Colaboratony (224246 Sa. .polaionesv k224345 Saad Ahmed - Copy of interpolation - k224345 Saad Ahmed - Copy of interpolation.csv(text/csv) - 55 bytes, last modified: 26/03/2024 - 100% done Saving 224345 Saad Aimed - Copy of interpolation ~ k224345 Saad Ahmed - Copy of in newton Forward Divided Difference polynomial. is: 16 3 8 7 6 5 0.3183 x = 0.4438 x ~ 0.4406 x + 4,292 x - 5.428 x ~ 5.479 x a 3 2 + 15.04 x» 2.875 x + 6.286 x = 36.9 x + 58.65 Interpolated value at x = 55 1s) 2.789911627388175er16 1e19 Newton Forward Divided Difference polynomial 10 os 08 oa 02 0.0} —¢——#__+__@-4— . . 0 20 40 60 80 100 Double-click (or enter) to edit htips:ifcola. research google.comidrvel 7GGWSUmFaHeMBhUSSCExGBINSTwAE2ro7authuser=2HscrolTo=Wirgrico2OW38prinMode=trus 13/13

You might also like