0% found this document useful (0 votes)
43 views30 pages

Adv Math Prog

The document contains code implementations of Newton-Raphson's method and the bisection method for solving nonlinear equations numerically in both C++ and Python languages. For Newton-Raphson's method, the code finds the real roots of a given nonlinear equation by taking the initial guess and iteratively computing new estimates using the derivative until convergence within a specified tolerance. For the bisection method, the code bisects the interval between two initial guesses bracketing the root and converges to the solution by successively narrowing the interval. The code provides sample outputs applying both methods to example functions to find their roots.

Uploaded by

Lev Shouyo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views30 pages

Adv Math Prog

The document contains code implementations of Newton-Raphson's method and the bisection method for solving nonlinear equations numerically in both C++ and Python languages. For Newton-Raphson's method, the code finds the real roots of a given nonlinear equation by taking the initial guess and iteratively computing new estimates using the derivative until convergence within a specified tolerance. For the bisection method, the code bisects the interval between two initial guesses bracketing the root and converges to the solution by successively narrowing the interval. The code provides sample outputs applying both methods to example functions to find their roots.

Uploaded by

Lev Shouyo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Don Mariano Marcos Memorial State

University Mid - La Union Campus


College of Engineering

“Computer Programming for Numerical Analysis”


(C++/ Python Language)
Newton-Raphson’s Method
(C++ Language)
/* Program: Finding real roots of nonlinear
equation using Newton Raphson Method
Author: CodeSansar
Date: November 18, 2018
*/#include<iostream>#include<iomanip>#include<math.h>#include<stdlib.h>
/* Defining equation to be solved.
Change this equation to solve another problem. */#define f(x) 3*x - cos(x) -1
/* Defining derivative of g(x).
As you change f(x), change this function also. */#define g(x) 3 + sin(x)
using namespace std;
int main(){
float x0, x1, f0, f1, g0, e;
int step = 1, N;

/* Setting precision and writing floating point values in fixed-point notation. */


cout<< setprecision(6)<< fixed;

/* Inputs */
cout<<"Enter initial guess: ";
cin>>x0;
cout<<"Enter tolerable error: ";
cin>>e;
cout<<"Enter maximum iteration: ";
cin>>N;

/* Implementing Newton Raphson Method */


cout<< endl<<"*********************"<< endl;
cout<<"Newton Raphson Method"<< endl;
cout<<"*********************"<< endl;
do
{
g0 = g(x0);
f0 = f(x0);
if(g0 == 0.0)
{
cout<<"Mathematical Error.";
exit(0);
}

x1 = x0 - f0/g0;

cout<<"Iteration-"<< step<<":\t x = "<< setw(10)<< x1<<" and f(x) =


"<< setw(10)<< f(x1)<< endl;
x0 = x1;

step = step+1;

if(step > N)
{
cout<<"Not Convergent.";
exit(0);
}

f1 = f(x1);

}while(fabs(f1)>e);
cout<< endl<<"Root is: "<< x1;
return 0;}

OUTPUT

Enter initial guess: 2


Enter tolerable error: 0.000001
Enter maximum iteration: 10

*********************
Newton Raphson Method
*********************
Iteration-1: x1 = 0.614547 and f(x1) = 0.026607
Iteration-2: x1 = 0.607108 and f(x1) = 0.000023
Iteration-3: x1 = 0.607102 and f(x1) = -0.000000

Root is: 0.607102

Newton-Raphson’s Method
(Python Language)
# Defining Functiondef f(x):
return x**3 - 5*x - 9
# Defining derivative of functiondef g(x):
return 3*x**2 - 5
# Implementing Newton Raphson Method
def newtonRaphson(x0,e,N):
print('\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')
step = 1
flag = 1
condition = True
while condition:
if g(x0) == 0.0:
print('Divide by zero error!')
break

x1 = x0 - f(x0)/g(x0)
print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, f(x1)))
x0 = x1
step = step + 1

if step > N:
flag = 0
break

condition = abs(f(x1)) > e

if flag==1:
print('\nRequired root is: %0.8f' % x1)
else:
print('\nNot Convergent.')

# Input Section
x0 = input('Enter Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')
# Converting x0 and e to float
x0 = float(x0)
e = float(e)
# Converting N to integer
N = int(N)

#Note: You can combine above three section like this# x0 = float(input('Enter Guess: '))# e =
float(input('Tolerable Error: '))# N = int(input('Maximum Step: '))
# Starting Newton Raphson Method
newtonRaphson(x0,e,N)

OUTPUT
Enter Guess: 2
Tolerable Error: 0.000001
Maximum Step: 10

*** NEWTON RAPHSON METHOD IMPLEMENTATION ***


Iteration-1, x1 = 3.571429 and f(x1) = 18.696793
Iteration-2, x1 = 3.009378 and f(x1) = 3.207103
Iteration-3, x1 = 2.864712 and f(x1) = 0.185915
Iteration-4, x1 = 2.855236 and f(x1) = 0.000771
Iteration-5, x1 = 2.855197 and f(x1) = 0.000000

Required root is: 2.85519654


Bisection Method
(C++ Language)

#include<iostream>#include<iomanip>#include<math.h>
/*
Defining equation to be solved.
Change this equation to solve another problem.
*/
#define f(x) cos(x) - x * exp(x)
using namespace std;
int main(){
/* Declaring required variables */
float x0, x1, x, f0, f1, f, e;
int step = 1;

/* Setting precision and writing floating point values in fixed-point notation. */


cout<< setprecision(6)<< fixed;

/* Inputs */
up:
cout<<"Enter first guess: ";
cin>>x0;
cout<<"Enter second guess: ";
cin>>x1;
cout<<"Enter tolerable error: ";
cin>>e;

/* Calculating Functional Value */


f0 = f(x0);
f1 = f(x1);
/* Checking whether given guesses brackets the root or not. */
if( f0 * f1 > 0.0)
{
cout<<"Incorrect Initial Guesses."<< endl;
goto up;
}
/* Implementing Bisection Method */
cout<< endl<<"****************"<< endl;
cout<<"Bisection Method"<< endl;
cout<<"****************"<< endl;
do
{
/* Bisecting Interval */
x = (x0 + x1)/2;
f = f(x);

cout<<"Iteration-"<< step<<":\t x = "<< setw(10)<< x<<" and f(x) = "<<


setw(10)<< f(x)<< endl;

if( f0 * f < 0)
{
x1 = x;
}
else
{
x0 = x;
}
step = step + 1;
}while(fabs(f)>e);
cout<< endl<< Root is: "<< x<< endl;

return 0;}
OUTPUT

Enter first guess: 0 Enter second guess: 1


Enter tolerable error: 0.00001

****************
Bisection Method
****************
Iteration-1: x = 0.500000 and f(x) = 0.053222
Iteration-2: x = 0.750000 and f(x) = -0.856061
Iteration-3: x = 0.625000 and f(x) = -0.356691
Iteration-4: x = 0.562500 and f(x) = -0.141294
Iteration-5: x = 0.531250 and f(x) = -0.041512
Iteration-6: x = 0.515625 and f(x) = 0.006475
Iteration-7: x = 0.523438 and f(x) = -0.017362
Iteration-8: x = 0.519531 and f(x) = -0.005404
Iteration-9: x = 0.517578 and f(x) = 0.000545
Iteration-10: x = 0.518555 and f(x) = -0.002427
Iteration-11: x = 0.518066 and f(x) = -0.000940
Iteration-12: x = 0.517822 and f(x) = -0.000197
Iteration-13: x = 0.517700 and f(x) = 0.000174
Iteration-14: x = 0.517761 and f(x) = -0.000012
Iteration-15: x = 0.517731 and f(x) = 0.000081
Iteration-16: x = 0.517746 and f(x) = 0.000035
Iteration-17: x = 0.517754 and f(x) = 0.000011
Iteration-18: x = 0.517757 and f(x) = -0.000000

Root is: 0.517757


Bisection Method
(Python Language)

# Defining Functiondef f(x):


return x**3-5*x-9
# Implementing Bisection Methoddef bisection(x0,x1,e):
step = 1
print('\n\n*** BISECTION METHOD IMPLEMENTATION ***')
condition = True
while condition:
x2 = (x0 + x1)/2
print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))

if f(x0) * f(x2) < 0:


x1 = x2
else:
x0 = x2

step = step + 1
condition = abs(f(x2)) > e

print('\nRequired Root is : %0.8f' % x2)

# Input Section
x0 = input('First Guess: ')
x1 = input('Second Guess: ')
e = input('Tolerable Error: ')
# Converting input to float
x0 = float(x0)
x1 = float(x1)
e = float(e)
#Note: You can combine above two section like this# x0 = float(input('First Guess: '))# x1 =
float(input('Second Guess: '))# e = float(input('Tolerable Error: '))

# Checking Correctness of initial guess values and bisectingif f(x0) * f(x1) > 0.0:
print('Given guess values do not bracket the root.')
print('Try Again with different guess values.')else:
bisection(x0,x1,e)
OUTPUT

First Guess: 2
Second Guess: 3
Tolerable Error: 0.00001

*** BISECTION METHOD IMPLEMENTATION ***


Iteration-1, x2 = 2.500000 and f(x2) = -5.875000
Iteration-2, x2 = 2.750000 and f(x2) = -1.953125
Iteration-3, x2 = 2.875000 and f(x2) = 0.388672
Iteration-4, x2 = 2.812500 and f(x2) = -0.815186
Iteration-5, x2 = 2.843750 and f(x2) = -0.221588
Iteration-6, x2 = 2.859375 and f(x2) = 0.081448
Iteration-7, x2 = 2.851562 and f(x2) = -0.070592
Iteration-8, x2 = 2.855469 and f(x2) = 0.005297
Iteration-9, x2 = 2.853516 and f(x2) = -0.032680
Iteration-10, x2 = 2.854492 and f(x2) = -0.013700
Iteration-11, x2 = 2.854980 and f(x2) = -0.004204
Iteration-12, x2 = 2.855225 and f(x2) = 0.000546
Iteration-13, x2 = 2.855103 and f(x2) = -0.001829
Iteration-14, x2 = 2.855164 and f(x2) = -0.000641
Iteration-15, x2 = 2.855194 and f(x2) = -0.000048
Iteration-16, x2 = 2.855209 and f(x2) = 0.000249
Iteration-17, x2 = 2.855202 and f(x2) = 0.000101
Iteration-18, x2 = 2.855198 and f(x2) = 0.000027
Iteration-19, x2 = 2.855196 and f(x2) = -0.000011
Iteration-20, x2 = 2.855197 and f(x2) = 0.000008

Required Root is : 2.85519695


Numerical Integration
(C++ Language)

#include<iostream>#include<conio.h>
using namespace std;
int main(){
float x[100], y[100], xp, yp=0, p;
int i,j,n;

/* Input Section */
cout<<"Enter number of data: ";
cin>>n;
cout<<"Enter data:"<< endl;
for(i=1;i<=n;i++)
{
cout<<"x["<< i<<"] = ";
cin>>x[i];
cout<<"y["<< i<<"] = ";
cin>>y[i];
}
cout<<"Enter interpolation point: ";
cin>>xp;

/* Implementing Lagrange Interpolation */


for(i=1;i<=n;i++)
{
p=1;
for(j=1;j<=n;j++)
{
if(i!=j)
{
p = p* (xp - x[j])/(x[i] - x[j]);
}
}
yp = yp + p * y[i];
}
cout<< endl<<"Interpolated value at "<< xp<< " is "<< yp;

return 0;}
OUTPUT

Enter number of data: 5


Enter data:
x[1] = 5
y[1] = 150
x[2] = 7
y[2] = 392
x[3] = 11
y[3] = 1452
x[4] = 13
y[4] = 2366
x[5] = 17
y[5] = 5202
Enter interpolation point: 9

Interpolated value at 9 is 810


Quadratic Interpolation
(Python Language)

# Lagrange Interpolation
# Importing NumPy Libraryimport numpy as np
# Reading number of unknowns
n = int(input('Enter number of data points: '))
# Making numpy array of n & n x n size and initializing # to zero for storing x and y value
along with differences of y
x = np.zeros((n))
y = np.zeros((n))

# Reading data pointsprint('Enter data for x and y: ')for i in range(n):


x[i] = float(input( 'x['+str(i)+']='))
y[i] = float(input( 'y['+str(i)+']='))

# Reading interpolation point


xp = float(input('Enter interpolation point: '))
# Set interpolated value initially to zero
yp = 0
# Implementing Lagrange Interpolationfor i in range(n):

p=1

for j in range(n):
if i != j:
p = p * (xp - x[j])/(x[i] - x[j])

yp = yp + p * y[i]
# Displaying outputprint('Interpolated value at %.3f is %.3f.' % (xp, yp))
OUTPUT

Enter number of data points: 5


Enter data for x and y:
x[0]=5
y[0]=150
x[1]=7
y[1]=392
x[2]=11
y[2]=1452
x[3]=13
y[3]=2366
x[4]=17
y[4]=5202
Enter interpolation point: 9
Interpolated value at 9.000 is 810.000.
Numerical Differentiation
(C++ Language)

#include <iostream>
#include <cmath>

using namespace std;

double f(double x) {
return sin(x); // define the function to differentiate
}

double central_diff(double x, double h) {


double f1 = f(x + h);
double f2 = f(x - h);
return (f1 - f2) / (2.0 * h); // calculate central difference
}

int main() {
double x = 1.0; // point at which to evaluate the derivative
double h = 0.001; // step size
double dfdx = central_diff(x, h); // approximate the derivative

cout << "The derivative of f(x) at x = " << x << " is " << dfdx << endl;

return 0;
}

OUTPUT
The Derivative of f(x) at x = 1 is
0.540302

Numerical Differentiation
(Python Language)

import numpy as np
import matplotlib.pyplot as plt

def diff(f, x, dx=1e-6):


numerator = f(x + dx) - f(x - dx) derivative =
numerator / ( 2.0 * dx ) return derivative
dx = 0.01
x=0
f = np.exp
derivative = diff(f, x, dx)
print("The approximate derivative of exp(x) at x = 0 is: %f. The error is %f."
% (derivative, abs(derivative - 1)))
x=0

def g(x):
return np.exp(-2*x)

derivative = diff(g, x, dx)


print('The approximate derivative of exp(-2*x) at x = 0 is:
{0:.5f}. The error is {1:.5f}.'
.format(derivative, abs(derivative - (-2.0))))

x=
2*np.pi f
= np.cos
derivative = diff(f, x, dx)
print('The approximate derivative of cos(x) at x = 2*pi is:
{0:.5f}. The error is {1:.5f}.'
.format(derivative, abs(derivative - 0)))

x=1
f = np.log
derivative = diff(f, x, dx)
print('The approximate derivative of ln(x) at x = 0 is: {0:.5f}. The error is {1:.5f}.'
.format(derivative, abs(derivative - 1)))

OUTPUT
The approximate derivative of exp(x) at x = 0 is: 1.000017. The error is 0.000017.
The approximate derivative of exp(-2*x) at x = 0 is: -2.00013. The error is 0.00013.
The approximate derivative of cos(x) at x = 2*pi is: 0.00000. The error is 0.00000.
The approximate derivative of ln(x) at x = 0 is: 1.00003

The error is 0.00003.

Numerical Integration
(C++ Language)

#include<stream>
#include<math.h>

/* Define function here */ #define


f(x) 1/(1+pow(x,2))

using namespace std;


int main()
{
float lower, upper, integration=0.0, stepSize, k;
int i, subInterval;

/* Input */
cout<<"Enter lower limit of integration: ";
cin>>lower;
cout<<"Enter upper limit of integration: ";
cin>>upper;
cout<<"Enter number of sub intervals: ";
cin>>subInterval;

/* Calculation */

/* Finding step size */


stepSize = (upper - lower)/subInterval;

/* Finding Integration Value */


integration = f(lower) + f(upper);

for(i=1; i<= subInterval-1; i++)


{
k = lower + i*stepSize;
integration = integration + 2 * (f(k));
}

integration = integration * stepSize/2;

cout<< endl<<"Required value of integration is: "<< integration;

return 0;

OUTPUT

Enter lower limit of integration: 0


Enter upper limit of integration: 6
Enter number of sub intervals: 6
Required value of integration is: 1.4108

Numerical Integration
(Python Language)

# Trapezoidal Method

# Define function to integrate def f(x):


return 1/(1 + x**2)

# Implementing trapezoidal method


def trapezoidal(x0,xn,n):
# calculating step size
h = (xn - x0) / n

# Finding sum
integration = f(x0) + f(xn)

for i in range(1,n):
k = x0 + i*h
integration = integration + 2 * f(k)

# Finding final integration value


integration = integration * h/2

return integration

# Input section
lower_limit = float(input("Enter lower limit of integration: "))
upper_limit = float(input("Enter upper limit of integration: "))
sub_interval = int(input("Enter number of sub intervals: "))

# Call trapezoidal() method and get result


result = trapezoidal(lower_limit, upper_limit, sub_interval)
print("Integration result by Trapezoidal method is: %0.6f" %
(result) )

OUTPUT

Enter lower limit of integration: 0


Enter upper limit of integration: 1
Enter number of sub intervals: 6
Integration result by Trapezoidal method is: 0.784241

You might also like