Guest User

Untitled

a guest
Oct 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import numpy as np
  2.  
  3. # Funkcje testowe
  4. def test_function_1(x):
  5. """Funkcja rosnąca z miejscem zerowym w x=100"""
  6. return np.power(x, 1.5)-x*10
  7.  
  8. def test_function_2(x):
  9. """Funkcja malejaca z miejscem zerowym w x=100"""
  10. return -np.power(x,1.5)+x*10
  11.  
  12.  
  13. def actual_test(regulafalsifun, test_fun):
  14. """Zestaw testów dla implementacji metody Regula Falsi
  15.  
  16. Parametry:
  17. regulafalsifun (function): Funkcja implementująca metodę Regula Falsi.
  18. test_fun (function): Funkcja testująca
  19. """
  20. # test prawidłowości wyniku
  21. a, b, M, sig, e = 1, 140, 100, 0.0000001, 0.0000001
  22. n,x,fx = regulafalsifun(test_fun, a, b, M, sig, e)
  23. assert n < M and fx <= e and 99.99 < x < 100.01, "błędne wyniki: {} {} {}".format(n, x, fx)
  24. # test przerwania obliczeń, gdy n > M
  25. a, b, M, sig, e = 1, 140, 10, 0.0000001, 0.00000000001
  26. n,x,fx = regulafalsifun(test_fun, a, b, M, sig, e)
  27. assert n == M, "błąd przerwania obliczeń gdy n > M, {} {} {}".format(n, x, fx)
  28. # test błędu, gdy sig(a) == sig(b)
  29. a, b, M, sig, e = 110, 140, 10, 0.0000001, 0.00000000001
  30. try:
  31. n,x,fx = regulafalsifun(test_fun, a, b, M, sig, e)
  32. except Exception:
  33. print("Wynik testu: pozytywny")
  34. else:
  35. "błąd - nie rzucono wyjątku gdy sig(a) == sig(b)"
  36.  
  37.  
  38. def regula_falsi(fun, a, b, M, sig, eps):
  39. """Znajdowanie pierwiastka funkcji metodą regula falsi
  40.  
  41. Parametry:
  42. fun (function): Badana funkcja.
  43. a (int): Początkowe x.
  44. b (int): Końcowe x.
  45. M (int): Maksymalna liczba iteracji.
  46. sig (float): Minimalna odległość a od b.
  47. e (float): Maksymalny błąd numeryczny."""
  48. if np.sign(fun(a)) == np.sign(fun(b)):
  49. raise Exception("sgn(fa) == sgn(fb)")
  50. for n in range(M):
  51. e = b - a
  52. x = b - (b - a)/(fun(b) - fun(a)) * fun(b)
  53. if np.abs(e) < sig or np.abs(fun(x)) < eps:
  54. return n+1, x, fun(x)
  55. if np.sign(fun(x)) != np.sign(fun(a)):
  56. b = x
  57. else:
  58. a = x
  59. return n+1, x, fun(x)
  60.  
  61.  
  62. def main():
  63. # wykonanie testów dla funkcji rosnącej
  64. actual_test(regula_falsi, test_function_1)
  65. # wykonanie testów dla funkcji malejącej
  66. actual_test(regula_falsi, test_function_2)
  67.  
  68.  
  69. if __name__=='__main__':
  70. main()
Add Comment
Please, Sign In to add comment