Skip to content

Instantly share code, notes, and snippets.

@navin-mohan
Last active June 14, 2019 17:05
Show Gist options
  • Save navin-mohan/21b48593615bafd4cf774b443a9b98c8 to your computer and use it in GitHub Desktop.
Save navin-mohan/21b48593615bafd4cf774b443a9b98c8 to your computer and use it in GitHub Desktop.
Newton-Raphson Method
/*
* ------------------------
* | Newton-Raphson Method |
* ------------------------
*
* Author: Navin Mohan
* Website: https://nvnmo.github.io
*
* MIT License
*
* Copyright (c) 2019 Navin Mohan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <iostream>
#include <cmath>
using namespace std;
double f(double x){
// the function
return log(x) - cos(x);
}
double f_prime(double x){
// the derivate
return 1/x + sin(x);
}
double approximate(double (*f) (double), double (*f_prime) (double),double x,int n){
while(n--){
// f_prime(x) is assumed to be non-zero
x = x - f(x)/f_prime(x);
}
return x;
}
int main(){
double x;
int n;
cout << "X0 = ";
cin >> x;
cout << "Number of iterations: ";
cin >> n;
cout << approximate(f,f_prime,x,n) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment