Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- # Funkcje testowe
- def test_function_1(x):
- """Funkcja rosnąca z miejscem zerowym w x=100"""
- return np.power(x, 1.5)-x*10
- def test_function_2(x):
- """Funkcja malejaca z miejscem zerowym w x=100"""
- return -np.power(x,1.5)+x*10
- def actual_test(regulafalsifun, test_fun):
- """Zestaw testów dla implementacji metody Regula Falsi
- Parametry:
- regulafalsifun (function): Funkcja implementująca metodę Regula Falsi.
- test_fun (function): Funkcja testująca
- """
- # test prawidłowości wyniku
- a, b, M, sig, e = 1, 140, 100, 0.0000001, 0.0000001
- n,x,fx = regulafalsifun(test_fun, a, b, M, sig, e)
- assert n < M and fx <= e and 99.99 < x < 100.01, "błędne wyniki: {} {} {}".format(n, x, fx)
- # test przerwania obliczeń, gdy n > M
- a, b, M, sig, e = 1, 140, 10, 0.0000001, 0.00000000001
- n,x,fx = regulafalsifun(test_fun, a, b, M, sig, e)
- assert n == M, "błąd przerwania obliczeń gdy n > M, {} {} {}".format(n, x, fx)
- # test błędu, gdy sig(a) == sig(b)
- a, b, M, sig, e = 110, 140, 10, 0.0000001, 0.00000000001
- try:
- n,x,fx = regulafalsifun(test_fun, a, b, M, sig, e)
- except Exception:
- print("Wynik testu: pozytywny")
- else:
- "błąd - nie rzucono wyjątku gdy sig(a) == sig(b)"
- def regula_falsi(fun, a, b, M, sig, eps):
- """Znajdowanie pierwiastka funkcji metodą regula falsi
- Parametry:
- fun (function): Badana funkcja.
- a (int): Początkowe x.
- b (int): Końcowe x.
- M (int): Maksymalna liczba iteracji.
- sig (float): Minimalna odległość a od b.
- e (float): Maksymalny błąd numeryczny."""
- if np.sign(fun(a)) == np.sign(fun(b)):
- raise Exception("sgn(fa) == sgn(fb)")
- for n in range(M):
- e = b - a
- x = b - (b - a)/(fun(b) - fun(a)) * fun(b)
- if np.abs(e) < sig or np.abs(fun(x)) < eps:
- return n+1, x, fun(x)
- if np.sign(fun(x)) != np.sign(fun(a)):
- b = x
- else:
- a = x
- return n+1, x, fun(x)
- def main():
- # wykonanie testów dla funkcji rosnącej
- actual_test(regula_falsi, test_function_1)
- # wykonanie testów dla funkcji malejącej
- actual_test(regula_falsi, test_function_2)
- if __name__=='__main__':
- main()
Add Comment
Please, Sign In to add comment