Use saved searches to filter your results more quickly
Cancel Create saved search
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.
Reload to refresh your session.
scrat98/newton-method
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Switch branches/tags
Branches Tags
Could not load branches
Nothing to show
Could not load tags
Nothing to show
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Cancel Create
- Local
- Codespaces
HTTPS GitHub CLI
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI.
Алгоритмы С#. Метод Ньютона для решения систем уравнений
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
Latest commit message
Commit time
README.MD
Отчет по лабораторной работе №2
Решение нелинейных уравнений методом Ньютона
Головко Артем М3209
Вариант 7
Напишем функцию на JavaScript для итерационного процесса Ньютона.
const math = require(«mathjs»); const log_table = require(«cli-table»); function newtonMethod(func, derivativeFunc, initialX, epsilon, dgt, maxIter) const result = new log_table( head: [«n», «x», «f(x)», «f'(x)», «h(n)»] >); let curX = initialX; for (let i = 0; i maxIter; i++) const funcVal = func(curX); const derivativeFuncVal = derivativeFunc(curX); const hVal = math.divide(funcVal, derivativeFuncVal); result.push([ `$i>`, `$math.format(curX, notation: «fixed», precision: dgt >)>`, `$math.format(funcVal, notation: «fixed», precision: dgt >)>`, `$math.format(derivativeFuncVal, notation: «fixed», precision: dgt >)>`, `$math.format(hVal, notation: «fixed», precision: dgt >)>` ]); if (Math.abs(hVal) epsilon) break; curX = math.subtract(curX, hVal); > return result; >
Теперь зададим константы и вызовем наш метод Ньютона
эпсилон (epsilon) = 10 6
количество знаков после запятой (dgt) = 8
максимальное количество итераций (maxIter) = 50
Метод Ньютона (метод касательных) Пример Решения
найдем X0 (initialX) = 10
зададим само выражение(expr) =
function evalToFunc(originalEval) return val => originalEval( x: val >); > const epsilon = 1e-6; const dgt = 8; const maxIter = 50; const initialX = 10; const expr = «3 — 0.5*sqrt(x) — exp(-0.5*x^2)»; const func = evalToFunc(math.parse(expr).compile().eval); const derivativeFunc = evalToFunc(math.derivative(expr, «x»).compile().eval); const result = newtonMethod( func, derivativeFunc, initialX, epsilon, dgt, maxIter ); console.log(`Expression: $expr>`); console.log(result.toString());
В итоге получим таблицу с результатом:
Источник: github.com
Решение нелинейного уравнения методом Ньютона — C (СИ)
при помощи метода Ньютона (там еще какой-то цикл). Я вообще не понимаю. Нужен самый элементарный код, как я понимаю, потому что после второй пары, нам это задали, я думаю, что должно быть простенькое. Помогите, пожалуйста . Все, чем могу помочь, это производная данной функции равна cos(x) +x -2 А еще я только что здесь зарегистрировалась и долго не могла понять куда и как писать (ну это так, вам для смеха )
Код к задаче: «Решение нелинейного уравнения методом Ньютона»
Листинг программы
#include #include double f(double x) //функция < return sin(x)-1/x; >double f1(double x) // первая производная функции, f’ < return cos(x)+1/(x*x) ; >double f2(double x) //вторая производная функции, f» < return 2/(x*x*x)-sin(x); >int main() < int n=0; double a=1,b=1.5; // отрезок [1,1.5] double c,eps=0.0001; // точность if(f(a)*f2(a)>0) c=a; else c=b; do < c=c-f(c)/f1(c); n++; >while (fabs(f(c))>=eps); // цикл ищет корень пока его значение больше заданой точности printf(«c=%lfn»,c); //вывод найденого корня printf(«n=%dn»,n); //вывод количества итераций return 0; >
Источник: studassistent.ru
Метод Ньютона в C ++
Сегодня мы рассмотрим, как реализовать метод Ньютона для нахождения приближений или корней вещественной функции на C++.
Решение производных и уравнений
Сначала нам нужно определить функции, которые решают формулу, и производную. Они выглядят следующим образом:
float solveEquation(float value) < // Уравнение: x^3 + 4x^2 -10 return pow(value, 3) + 4 * pow(value, 2) — 10; > float solveDerivative(float value) < // Уравнение: 2x^2 + 8x return pow((2 * value), 2) + 8 * value; >Code language: JavaScript (javascript)
Эти функции будут вызываться для каждого значения в последующем цикле.
Метод Ньютона в C++
Далее мы можем реализовать метод Ньютона в C++ следующим образом:
#include #include using namespace std; float solveEquation(float value) < // Уравнение: x^3 + 4x^2 -10 return pow(value, 3) + 4 * pow(value, 2) — 10; > float solveDerivative(float value) < // Уравнение: 2x^2 + 8x return pow((2 * value), 2) + 8 * value; > int main() < int iterator = 0; float xi = 0.75; float xi_xi = 0; float last_xi = 0; printf(«Метод Ньютонаn»); printf(«Задача: x^3 + 4x^2 -10n»); printf(«Производная: 2x^2 + 8xnnn»); printf(«+—-+————-+————-+————-+————-+——-» «——+n»); printf(«+ i | xi | f(xi) | f'(xi) | xi + 1 | » «xi_xi |n»); printf(«+—-+————-+————-+————-+————-+——-» «——+n»); while (1) < float fxi = solveEquation(xi); float _fxi = solveDerivative(xi); float xi_1 = xi — (fxi / _fxi); printf(«|%3d |%12.8f |%12.8f |%12.8f |%12.8f |%12.8f|n», iterator, xi, fxi, _fxi, xi_1, xi_xi); iterator++; last_xi = xi; xi = xi_1; xi_xi = abs(xi — last_xi); if (xi_xi == 0) < printf(«+—-+————-+————-+————-+————-+—» «———+n»); break; > > >Code language: PHP (php)
Как вы можете видеть, мы создаем бесконечный цикл, который прервется только тогда, когда xi_xi будет равен 0. Также мы используем функцию abs.
Внутри цикла мы также вызываем solveEquation и solveDerivative для каждого значения, выводим и выводим их с помощью printf.
В нашем случае, если я запускаю программу, результат выглядит следующим образом:
Источник: dvsemenov.ru