This code defines a function `solveByIteration` that uses the Newton-Raphson...

November 21, 2023 at 09:06 AM

#include <iostream> #include <cmath> #include <iomanip> #include <Windows.h> double solveByIteration(double (*f)(double), double (*df)(double), double x0, double epsilon, int maxIterations) { double x = x0; for (int i = 0; i < maxIterations; ++i) { double deltaX = f(x) / df(x); x -= deltaX; if (std::abs(deltaX) < epsilon) { return x; } } std::cerr << "Не вдалося досягти заданої точності за максимальну кількість ітерацій." << std::endl; return std::numeric_limits<double>::quiet_NaN(); } double equation(double x) { return 0.25 * std::pow(x, 3) + x - 1.2502; } double derivative(double x) { return 0.75 * std::pow(x, 2) + 1; } int main() { SetConsoleOutputCP(1251); SetConsoleCP(1251); double epsilon, initialGuess; int maxIterations; std::cout << "Введіть початкове припущення: "; std::cin >> initialGuess; std::cout << "Введіть точність (epsilon): "; std::cin >> epsilon; std::cout << "Введіть максимальну кількість ітерацій: "; std::cin >> maxIterations; double result = solveByIteration(equation, derivative, initialGuess, epsilon, maxIterations); if (!std::isnan(result)) { std::cout << "Вирішення рівняння: x = " << std::setprecision(10) << result << std::endl; } return 0; }

This code defines a function solveByIteration that uses the Newton-Raphson method to find the root of a given equation. The equation and its derivative are passed as function pointers to the solveByIteration function.

The solveByIteration function takes an initial guess x0, a desired precision epsilon, and a maximum number of iterations maxIterations. It iteratively updates the value of x using the formula x = x - f(x) / df(x), where f(x) is the equation and df(x) is its derivative. It stops iterating when the absolute value of the change in x is less than epsilon, and returns the final value of x.

The main function prompts the user to enter the initial guess, precision, and maximum number of iterations. It then calls the solveByIteration function with the equation and derivative functions, and prints the result if it is not NaN.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node