Created
September 19, 2020 10:25
-
-
Save nandanhere/8b3db51d3c914a6766bff97f8a07d0c9 to your computer and use it in GitHub Desktop.
[Regular Falsi Method] Algorithm to calculate the root of the given equation using swift #swift #regularfalsimethod
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
import Foundation | |
import Darwin | |
let e = Darwin.M_E | |
let pi = Double.pi | |
// attempt to make newton rhapson method derived algo | |
// note that the trignometric values are in radians | |
// How to represent certain functions : | |
/// log base 10 : log10(float) | |
/// log base e : log(float) | |
/// power to function : pow(x, y) -> gives x ^ y | |
// note that you have to provide the values of xn and xnn | |
var xn = 1.0 | |
// make x a float value | |
var xnn = 2.0 // higher value | |
let precision = 3.0 // keep precision as double | |
var Fn = 0.0 // stores the value of F(xn) | |
var fn = 0.0 // stores the value of f(xn) | |
var Fnn = 0.0 // stores the value of F(x(n + 1)) | |
var fnn = 0.0 // stores the value of f(x(n + 1)) | |
// you need to provide the functions explicitly.. its too complex to do differentiation in swift | |
func firstExpression(_ x :Double) -> Double{ | |
//Enter the values of F(x) here | |
let res = (x * x * x * x ) - 12 | |
return res | |
} | |
print("x0 : \(xn)") | |
print("F(x0) = \(firstExpression(xn))") | |
var flip = 0 | |
var prev = 0.0 | |
var i = 0 | |
var temp = xnn + 1 // done as a security measure | |
while true | |
{ | |
Fnn = firstExpression(xnn) | |
Fn = firstExpression(xn) | |
print("x\(i + 1) : \(xnn)") | |
print("F(x\(i + 1)) = \(Fnn)") | |
var digi = xnn - (Fnn * (xnn - xn) / (Fnn - Fn)) | |
if firstExpression(digi) > 0 && digi < xnn { | |
temp = xnn | |
xnn = digi | |
} | |
else | |
if firstExpression(digi) < 0 && xn < digi | |
{temp = xn | |
xn = digi | |
} | |
print("\nx\(i + 2) = \(digi)") | |
print("F(x\(i + 2)) = \(firstExpression(digi))") | |
i += 1 | |
if flip == 1 {break} | |
if round(xnn * pow(10, precision ) ) == round(temp * pow(10, precision ) ) || round(xn * pow(10, precision ) ) == round(temp * pow(10, precision) ) { flip += 1 } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment