Skip to content

Instantly share code, notes, and snippets.

@nandanhere
Last active September 19, 2020 10:25
Show Gist options
  • Save nandanhere/c1bf7eac44e811738767fc394a5bec8b to your computer and use it in GitHub Desktop.
Save nandanhere/c1bf7eac44e811738767fc394a5bec8b to your computer and use it in GitHub Desktop.
[Newton Rhapson method in swift] A simple program to print the values obtained in newton rhapson method till the desired value is met till the given precision value #swift #newton_rhapson_method #iteration
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
var xn = pi// make x a float value
let precision = 4.0 // keep precision as double
var F = 0.0 // stores the value of F(x)
var f = 0.0 // stores the value of f(x)
// 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 = cos(x) + (x * sin(x))
return res
}
func derivedExpression(_ x : Double) -> Double{
// Enter the values of f(x) here
let res = x * cos(x)
return res
}
print("x0 : \(xn)")
var i = 0
var temp = 0.0
while true
{
F = firstExpression(xn)
f = derivedExpression(xn)
print("F(x\(i)) = \(F)")
print("f(x\(i)) = \(f)")
temp = xn
xn = xn - (F/f)
print("\nx\(i + 1) = \(xn)")
i += 1
if (Int(xn * pow(10,precision + 1)) == Int(temp * pow(10,precision + 1))) {break}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment