Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need a basic javascript program to find a root, using the Secant Method and Newt

ID: 3811714 • Letter: N

Question

Need a basic javascript program to find a root, using the Secant Method and Newton Method, for an equation of the form f(x)=0, however you will be starting with ONE guess instead of two.

The first method is called Newton's method or Newton-Raphson and it requires that you calculate the derivative of the function (by hand)

The second method uses any one of the the finite difference approximations to the derivative which you had written in Assignment One.

You might want to test your program with the equation ln(sin(x)) = -0.25

Note: make sure you know how to calculate the naperian logarithm in javascript

Note: x needs to be in radians

Note: use an initial approximation of x=1

by the way, you might want to check your answer with a calculator, it should be around

x= 0.8927517423921186

Explanation / Answer

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double f(double x); //declare the function for the given equation
double f(double x) //define the function here, ie give the equation
{
double a=pow(x,3)-x-11.0; //write the equation whose roots are to be determined
return a;
}
int main()
{
cout.precision(4);
cout.setf(ios::fixed); //set the precision of the output
double a,b,c,e;
cout<<"Enter the initial guess a=";
cin>>b;
cout<<"b= "; //take an intial guess
cin>>c;
cout<<"Enter the degree of accuracy ";
cin>>e; //take the desired accuracy
do
{
a=b;
b=c; //make b equal to the last calculated value of c
c=b-(b-a)/(f(b)-f(a))*f(b); //calculate c
if (f(c)==0)
{
cout<<" The root of the equation is "<<c; //print the root
return 0;
}
}while(abs(c-b)>=e); //check if the error is greater than the desired accuracy
cout<<" The root of the equation is "<<c; //print the root
return 0;
}

Output :

Enter the initial guess
a=5
b=
7
Enter the degree of accuracy
0.01

The root of the equation is 2.3737
--------------------------------
Process exited after 23.38 seconds with return value 0
Press any key to continue . . .

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote