Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Creator _Sabyasachi
- import numpy as np
- import matplotlib.pyplot as plot
- total_iteration = 1
- number_of_iteration = 1
- def plotting(z):
- to_return = (z / (1 - z)) * (np.sqrt(6 / (2 + z))) - .05
- return to_return
- def graph(k):
- y = plotting(k)
- plot.figure(figsize=(5, 5))
- plot.plot(k, y)
- plot.grid()
- plot.show()
- def secant_method(func, first_guess, second_guess, relative_error, max_iteration):
- global total_iteration
- p = 0.0
- if func(first_guess) * func(second_guess) > 0:
- return None
- while total_iteration < max_iteration and np.abs(second_guess - first_guess) > relative_error:
- try:
- a = first_guess
- b = second_guess
- p = (a*func(b) - b*func(a))/(func(b) - func(a))
- except ZeroDivisionError:
- print("Error! - Divided by zero")
- exit(-1)
- first_guess = second_guess
- second_guess = p
- total_iteration += 1
- if abs(func(second_guess)) > relative_error:
- print("Secant fails after ", total_iteration, " number of iteration")
- total_iteration = -1
- return p
- def false_position_method(func, lower_bracket, upper_bracket, app_error, max_iteration):
- global number_of_iteration
- fa = func(lower_bracket)
- while number_of_iteration <= max_iteration:
- a = lower_bracket
- b = upper_bracket
- p = (a * func(b) - b * func(a)) / (func(b) - func(a))
- fp = func(p)
- if fp == 0 or np.abs(func(p)) <= app_error:
- return p
- elif fp * fa >= 0:
- fa = fp
- lower_bracket = p
- else:
- upper_bracket = p
- number_of_iteration += 1
- return None
- x = np.arange(-1.9, 1, 0.1)
- graph(x)
- tolerable_error = 5e-3
- iteration_counter = int(input("Enter the maximum number of iteration for Secant and False Position Method : "))
- initial_guess = float(input("Enter 1st initial guess for Secant Method : "))
- initial_guess_2 = float(input("Enter 2nd initial guess for Secant Method : "))
- lower_bound = float(input("Enter lower bound of the bracket for False Position Method : "))
- upper_bound = float(input("Enter upper bound of the bracket for False Position Method : "))
- sect_method = secant_method(plotting, initial_guess, initial_guess_2, tolerable_error, iteration_counter)
- print()
- print("Showing the result for Secant Method :")
- if total_iteration > 0:
- print("Result found between the given interval ")
- print("Result :", sect_method, " iteration:", total_iteration)
- else:
- print("No result found between the given interval :'( \nGood Luck!")
- fpm = false_position_method(plotting, lower_bound, upper_bound, tolerable_error, iteration_counter)
- print("Showing the result for FP Method :")
- if number_of_iteration > 0:
- print("Result found between the given interval ")
- print("Result :", fpm, " iteration:", number_of_iteration)
- else:
- print("No result found between the given interval :'( \nGood Luck!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement