SHARE
TWEET

LAB 3

a guest Mar 25th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. import math as mt
  3. ######TASK 1
  4.  
  5. #nodes = int(input("Enter the number of nodes: "))
  6.  
  7. ### FUNCTION TO BE INTERPOLATED
  8.  
  9. def myFunction(x):
  10.     return x**10 + x**4 + 3*x**2 - 2*x + 1
  11.  
  12.  
  13. ### TASK 1 & 2
  14. ### set chebyshev to true to use chebyshev nodes
  15.  
  16. def interpolation(nodes, a, b, point, chebyshev=False):
  17.     step = (b-a)/(nodes-1)
  18.     Matrix = np.zeros([3,nodes])
  19.  
  20.     if chebyshev == False:
  21.         for i in range(0, nodes):
  22.             Matrix[0][i] = a + i*step
  23.             Matrix[1][i] = myFunction(Matrix[0][i])
  24.     else:
  25.         for i in range(0,nodes):
  26.             xi = mt.cos(mt.pi * (2*i + 1) / (2*nodes + 2))
  27.             zi = 0.5*((b-a)*xi + a + b)
  28.             Matrix[0][i] = zi
  29.             Matrix[1][i] = myFunction(Matrix[0][i])
  30.  
  31.     for i in range(0,nodes):
  32.         nominator = 1
  33.         denominator = 1
  34.         for n, k in enumerate(Matrix[0]):
  35.             if n != i:
  36.                 val = (point-k)
  37.                 nominator *= val
  38.                 val = (Matrix[0][i]-k)
  39.                 denominator *= val
  40.        
  41.         Matrix[2][i] = nominator/denominator * Matrix[1][i]
  42.     return sum(Matrix[2])
  43.  
  44. ### TASK 3
  45.  
  46. def maxError(a, b, step=0.01):
  47.     maxim = abs(interpolation(31, a, b, a, True) - myFunction(a))
  48.     maxIndex = a
  49.     for i in np.arange(a+step, b, step):
  50.         val = abs(interpolation(31, a, b, i, True) - myFunction(i))
  51.         if val > maxim:
  52.             maxim = val
  53.             maxIndex = i
  54.  
  55.     return maxIndex, maxim
  56.  
  57.  
  58. ### TESTS
  59.  
  60. #print(interpolation(5,0,6.28,mt.pi/6))
  61. #print(interpolation(31, -5, 5, 7, True))
  62. #print(interpolation(31, -5, 5, 7, False))
  63. #print(myFunction(7))
  64.  
  65. print(myFunction(7))
  66. print(interpolation(31, 0, 8, 7, True))
  67. ind, valueMax = maxError(-30.0, 30.0)
  68. print(ind, valueMax)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top