Pella86

Bisezione vs Netwon Plot

Feb 5th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. from matplotlib import pyplot as plt
  2. import struct
  3. import numpy as np
  4. import math
  5. from scipy import stats
  6.  
  7.  
  8. # read the data from the program Bisection
  9. def read_data(filename, datasize):
  10.     with open(filename, "rb") as f:
  11.       lines = f.read()
  12.      
  13.     print(f"File {filename} Read ", len(lines), "bytes")
  14.    
  15.     data = struct.unpack('d'*datasize*2 + "i"*datasize, lines);
  16.    
  17.     # first bite packet are the tolear
  18.     tolerance_values = data[:datasize]
  19.     result_values = data[datasize: datasize*2]
  20.     iteration_values = data[datasize*2:]
  21.     return tolerance_values, result_values, iteration_values
  22.  
  23. # calculate the error in log form
  24. def calc_error(teo_y, y):
  25.     erry = []
  26.     for v in y:
  27.         print("value:", v, end=" ")
  28.         err = (teo_y - v) / teo_y
  29.  
  30.         if err != 0:
  31.             err = np.log10(abs(err))
  32.             erry.append(err)
  33.             print("log10(error)", err)
  34.         else:
  35.             print("Max precision reached")
  36.             erry.append(min(erry))
  37.        
  38.     return erry
  39.  
  40. #plot and evaluate the data points
  41. def plot_eval(filename, datasize, teo_y):
  42.     # read the data
  43.     _, y, i = read_data(filename, datasize)
  44.     # calculate the errro
  45.     erry = calc_error(teo_y, y)
  46.     plt.plot(i, erry)
  47.    
  48.     slope, intercept, r_value, p_value, std_err = stats.linregress(i,erry)
  49.     print("y = " + str(slope) + "x + ", intercept)
  50.     print("angular coeff.:", math.tan(slope))    
  51.  
  52.  
  53. # fixed parameters
  54. datasize = 10
  55. teo_y = math.sqrt(2)
  56.            
  57. # newton
  58. filename = "./Bisezione/newton_data.dat"
  59. plot_eval(filename, datasize, teo_y)
  60.  
  61.  
  62. filename = "./Bisezione/bisezione_data.dat"
  63. plot_eval(filename, datasize, teo_y)
  64.  
  65. plt.title('Error in function of iterations')
  66. plt.xlabel('Number of iterations')
  67. plt.ylabel('log(error)')
  68.  
  69. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment