Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.15 KB | None | 0 0
  1. import time
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import sys
  5.  
  6. def read_inputs(filename):
  7.     """
  8.    Given a filename containing abscissaes and ordinates, returns the actual
  9.    values.
  10.    """
  11.     with open(filename) as f:
  12.         x, y = [], []
  13.         for line in f.readlines():
  14.             coord = [float(n) for n in line.strip().split()]
  15.             x.append(coord[0])
  16.             y.append(coord[1])
  17.     return np.array(x), np.array(y)
  18.  
  19.  
  20. def newton_differences(x, y):
  21.     """
  22.    Returns the newton difference of the given abscissaes and ordinates.
  23.    """
  24.     n = len(x)
  25.     a = []
  26.     for i in range(n):
  27.         a.append(y[i])
  28.  
  29.     for j in range(1, n):
  30.  
  31.         for i in range(n - 1, j - 1, -1):
  32.             a[i] = float(a[i] - a[i - 1]) / float(x[i] - x[i - j])
  33.  
  34.     return np.array(a)
  35.  
  36.  
  37. def Horner(abscissaes, newton_diff, x):
  38.     # Reverse iteration, starting from the end makes it easier.
  39.     value = newton_diff[-1]
  40.     for i, abscissae in reversed(list(enumerate(abscissaes[:-1]))):
  41.         term = newton_diff[i]
  42.         value = term + (x - abscissae) * value
  43.     return value
  44.  
  45.  
  46. def write_to_files(newton_diff_filename, graph_points_filename, npoints,
  47.                    abscissaes, newton_diff, a, b):
  48.     """
  49.    Writes the newton difference in the first file, and the points of the
  50.    graph in the second file.
  51.    """
  52.     with open(newton_diff_filename, "w") as f:
  53.         f.writelines(["%.20f\t" % item for item in newton_diff])
  54.  
  55.     # we create a mesh of npoints abscissae equidistant from each other by distance step
  56.     x = a
  57.     step = (b - a) / float(npoints - 1)
  58.     with open(graph_points_filename, "w") as f:
  59.         for i in range(npoints):
  60.             y = Horner(abscissaes, newton_diff, x)
  61.             f.write("{:.20f}\t{:.20f}\n".format(x, y))
  62.             x = x + step
  63.  
  64.  
  65. abscissaes, ordinates = read_inputs("table.txt")
  66. newton_diff = newton_differences(abscissaes, ordinates)
  67. write_to_files(
  68.     "divded_differences.txt",
  69.     "function_to_plot.txt",
  70.     100000,  # npoints
  71.     abscissaes,
  72.     newton_diff,
  73.     0,   # a
  74.     10,  # b
  75. )
  76.  
  77. def main():
  78.     try:
  79.         name = sys.argv[1]
  80.         numits = int(sys.argv[2])
  81.     except:
  82.         print('Usage: python %s <filename> <nb points>' % sys.argv[0])
  83.         print('Example: python %s table.txt 1000' % sys.argv[0])
  84.  
  85.     # we read from the table and ensure that abscissae are at distances larger than 1.e-10 from each other
  86.     x, y = read_from_file(name)
  87.     print("Your abscissae ", x)
  88.     print("Your ordinates ", y)
  89.     print("This is a representation of the points in the Cartesian plane:")
  90.  
  91.     a = min(x) - 0.005  # you need to modify this based on how
  92.     b = max(x) + 0.005  # wide you want your graph to be
  93.     diff = newton_differences(x, y)
  94.     write_to_files("divided_differences.txt", "function_to_plot.txt", numits, x, diff, a, b )
  95.  
  96.     x, y = read_from_file("table.txt")
  97.     plt.plot([x], [y], 'ro')
  98.     plt.axes().set_aspect('equal', 'datalim')
  99.     plt.xlabel('abscissae')
  100.     plt.ylabel('ordinates')
  101.     plt.title('Graph of the original points')
  102.     plt.show()
  103.  
  104.  
  105.  
  106.  
  107. if __name__ == '__main__':
  108.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement