0% found this document useful (0 votes)
2 views

cpp code

The document is a C++ program that calculates the cube root of a given value using the Newton-Raphson method. It handles both positive and negative inputs, returning the cube root for positive values and the negation of the cube root for negative values. The program includes a main function that prompts the user for input and displays the result with high precision.

Uploaded by

428akotilingala
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

cpp code

The document is a C++ program that calculates the cube root of a given value using the Newton-Raphson method. It handles both positive and negative inputs, returning the cube root for positive values and the negation of the cube root for negative values. The program includes a main function that prompts the user for input and displays the result with high precision.

Uploaded by

428akotilingala
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <iostream>

#include <iomanip>
using namespace std;

double value;

// Function to calculate the cube root using Newton-Raphson method


double root(double v) {
if (v == 0) {
return 0; // Cube root of 0 is 0
}

double a = 1; // Initial guess for the cube root


double next_a;

// Perform three explicit Newton-Raphson steps


next_a = (2 * a + v / (a * a)) / 3; // First step
a = (2 * next_a + v / (next_a * next_a)) / 3; // Second step
next_a = (2 * a + v / (a * a)) / 3; // Third step

// While loop to refine the approximation


while (next_a < a) {
a = next_a; // Update the current approximation
next_a = (2 * a + v / (a * a)) / 3; // Compute the next approximation
}

return a;
}

int main() {
cout << "Enter a value: ";
cin >> value;

if (value < 0) {
// For negative values, calculate the cube root of the absolute value and
negate the result
double positive_root = root(-value); // Take the cube root of the absolute
value
cout << "The cube root of " << value << " is: " << setprecision(15) << -
positive_root << endl;
} else {
// For non-negative values, calculate the cube root
cout << "The cube root of " << value << " is: " << setprecision(15) <<
root(value) << endl;
}

return 0;
}

You might also like