Python-Math-Algorithms/newton_polynom/__init__.py

50 lines
1.7 KiB
Python
Raw Normal View History

2023-04-25 13:37:03 +00:00
# Python module for calculating the newton polynom from given points
# _ _ _ _
# __ ___ __(_) |_| |_ ___ _ __ | |__ _ _
# \ \ /\ / / '__| | __| __/ _ \ '_ \ | '_ \| | | |
# \ V V /| | | | |_| || __/ | | | | |_) | |_| |
# \_/\_/ |_| |_|\__|\__\___|_| |_| |_.__/ \__, |
# |___/
# ____ __ __ _
# / ___|_ _____ _ __ \ \ / /__ __ _ ___| |
# \___ \ \ / / _ \ '_ \ \ \ / / _ \ / _` |/ _ \ |
# ___) \ V / __/ | | | \ V / (_) | (_| | __/ |
# |____/ \_/ \___|_| |_| \_/ \___/ \__, |\___|_|
# |___/
# Licensed under the GPLv2 License, Version 2.0 (the "License");
# Copyright (c) Sven Vogel
2023-04-25 14:27:32 +00:00
def combine_n(points):
k = len(points)
2023-04-25 13:37:03 +00:00
if k == 1:
2023-04-25 14:27:32 +00:00
return points[0][1]
elif k == 2:
return (points[1][1] - points[0][1]) / (points[1][0] - points[0][0])
2023-04-25 13:37:03 +00:00
else:
2023-04-25 14:27:32 +00:00
return (combine_n(points[1:k]) - combine_n(points[0:(k - 1)])) / (points[k - 1][0] - points[0][0])
2023-04-25 13:37:03 +00:00
2023-04-25 14:27:32 +00:00
# returns a polynom that will intersect all supplied points as long as
# the number of points is bigger than 1
def newton_polynom(points):
2023-04-25 17:18:06 +00:00
polynom = ""
2023-04-25 14:27:32 +00:00
for x in range(1, len(points)):
2023-04-25 13:37:03 +00:00
2023-04-25 14:27:32 +00:00
if x == 1:
2023-04-25 17:18:06 +00:00
polynom += '{r0:.2f} + '.format(r0=points[0][1])
2023-04-25 14:27:32 +00:00
else:
2023-04-25 17:18:06 +00:00
polynom += ' + '
2023-04-25 13:37:03 +00:00
2023-04-25 17:18:06 +00:00
polynom += "{r:.2f}".format(r=combine_n(points[0:(x + 1)]))
2023-04-25 13:37:03 +00:00
for y in range(x):
2023-04-25 17:18:06 +00:00
polynom += " * (x - {value:.2f})".format(value=points[y][0])
return polynom
2023-04-25 13:37:03 +00:00
def test():
2023-04-25 17:18:06 +00:00
points = [[-1, 5], [2, -1], [3, -1], [4, 5], [8, 9]]
print("newton polynom: ", newton_polynom(points))