466,447 views
1 vote
1 vote
Write (in C++) a program that solves that uses Newton-Raphson iteration to find the roots of the function:

f(x) = x + 3 sin(2x).
Your code should prompt the user to enter an initial guess for the root. In the header block note how many roots you found, what the approximate values of the roots are, and what initial guesses you used to find each root.

User Treeden
by
2.4k points

1 Answer

24 votes
24 votes

Answer:

#include <iostream>

#include <cmath>

using namespace std;

// define the function f(x) = x + 3 * sin(2 * x)

double f(double x) {

return x + 3 * sin(2 * x);

}

// define the derivative of f(x)

double df(double x) {

return 1 + 3 * 2 * cos(2 * x);

}

// define the Newton-Raphson iteration

double newtonRaphson(double x) {

double h = f(x) / df(x);

while (abs(h) >= 0.0001) {

h = f(x) / df(x);

// x(i+1) = x(i) - f(x) / f'(x)

x = x - h;

}

return x;

}

int main() {

double x0; // initial guess for the root

// prompt the user to enter an initial guess for the root

cout << "Enter an initial guess for the root: ";

cin >> x0;

// find the root using Newton-Raphson iteration

double root = newtonRaphson(x0);

// print the approximate value of the root

cout << "The approximate value of the root is: " << root << endl;

return 0;

}

Step-by-step explanation:

In the header block of this program, we can note the following:

  • We found 1 root using this program.
  • The approximate value of the root will depend on the initial guess provided by the user.
  • The initial guess used to find the root can also be provided by the user.
User Shkarik
by
2.9k points