Created
May 2, 2016 13:51
-
-
Save AFAgarap/eaf8e3c495149d1a8b8d8e62b762b271 to your computer and use it in GitHub Desktop.
Bisection method for finding root of f(x)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def main(): | |
A = 0; B = 12 | |
while True: | |
C = (A + B) / 2 | |
val_a = evaluate_function(A) | |
val_b = evaluate_function(B) | |
val_c = evaluate_function(C) | |
sign_a = determine_sign(val_a) | |
sign_b = determine_sign(val_b) | |
sign_c = determine_sign(val_c) | |
# the machine used for the development could | |
# only display up to x10^-15 | |
if (abs(A - B) <= (10**(-16))): | |
break | |
else: | |
if sign_a == sign_c: | |
A = C | |
elif sign_b == sign_c: | |
B = C | |
print("\nBisection method\n\nValue of X[0] = 0, X[1] = 12\nRoot of f(x):", C, "\n") | |
def determine_sign(value): | |
if value < 0: | |
return 0 # we shall use 0 to denote negative | |
elif value > 0: | |
return 1 # we shall use 1 to denote positive | |
else: | |
return None | |
def evaluate_function(value): | |
"Substitute A, B, C in the f(x)" | |
return 3**(3 * value + 1) - 7 * 5**(2 * value) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment