Skip to content

Commit 5483064

Browse files
jainanmol123cclauss
authored andcommitted
Create newton_forward_interpolation.py (TheAlgorithms#333)
* Create newton_forward_interpolation.py This code is for calculating newton forward difference interpolation for fixed difference. * Add doctests and reformat with black
1 parent 9226856 commit 5483064

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/
2+
3+
import math
4+
5+
# for calculating u value
6+
def ucal(u, p):
7+
"""
8+
>>> ucal(1, 2)
9+
0
10+
>>> ucal(1.1, 2)
11+
0.11000000000000011
12+
>>> ucal(1.2, 2)
13+
0.23999999999999994
14+
"""
15+
temp = u
16+
for i in range(1, p):
17+
temp = temp * (u - i)
18+
return temp
19+
20+
21+
def main():
22+
n = int(input("enter the numbers of values"))
23+
y = []
24+
for i in range(n):
25+
y.append([])
26+
for i in range(n):
27+
for j in range(n):
28+
y[i].append(j)
29+
y[i][j] = 0
30+
31+
print("enter the values of parameters in a list")
32+
x = list(map(int, input().split()))
33+
34+
print("enter the values of corresponding parameters")
35+
for i in range(n):
36+
y[i][0] = float(input())
37+
38+
value = int(input("enter the value to interpolate"))
39+
u = (value - x[0]) / (x[1] - x[0])
40+
41+
# for calculating forward difference table
42+
43+
for i in range(1, n):
44+
for j in range(n - i):
45+
y[j][i] = y[j + 1][i - 1] - y[j][i - 1]
46+
47+
summ = y[0][0]
48+
for i in range(1, n):
49+
summ += (ucal(u, i) * y[0][i]) / math.factorial(i)
50+
51+
print("the value at {} is {}".format(value, summ))
52+
53+
54+
if __name__ == "__main__":
55+
main()

0 commit comments

Comments
 (0)