【C++ 程序】 牛顿迭代法求一元二次方程的解(包括复数解)

程序

#include <iostream>
#include <cmath>
using namespace std;

double epsilon = 1E-15;
double a, b, c;

double f(double x)
{
	return a * x * x + b * x + c;
}

double derivative(double x)
{
	return (2 * a * x + b);
}

double calculation_once(double& x)
{
	x -= f(x) / derivative(x);
	return f(x);
}

int main()
{

	cout << "This is a programme using Newton's method to solve formulas." << endl;
	cout << "Input a,b,c for a*x^2 + b*x + c = 0." << endl;
	cout << "a = ";
	cin >> a;
	cout << "b = ";
	cin >> b;
	cout << "c = ";
	cin >> c;
	cout << "------------------------------" << endl;
	if (a == 0)
	{
		if (b == 0)
		{
			if (c == 0)
				cout << "Infinite solutions!" << endl;
			else cout << "No solution!" << endl;
		}
		else cout << "x = " << -c / b << endl;
	}
	else // a != 0
	{
		double difference;
		double x = 1 - b / (2 * a); // the right side
		do
		{
			difference = calculation_once(x);
			if (x < -b / (2 * a)) // no real solution
			{
				// x = m + ni
				double m = -b / (2 * a);
				double n = sqrt(f(m) / a);
				cout << "x1 = " << m << "-" << n << "i , x2 = " << m << "+" << n << "i" << endl;
				return 0;
			}
			else if (x == -b / (2 * a))
			{
				if (fabs(difference) < epsilon) cout << "x = " << -b / (2 * a) << endl;
				else cout << "x = " << x << endl;
				return 0;
			}
		} while (fabs(difference) > epsilon);
		if (x + b / (2 * a) <= sqrt(epsilon)) cout << "x = " << ((-b / (2 * a) == -0) ? 0 : -b / (2 * a)) << endl;
		else cout << "x1 = " << -b / a - x << " , x2 = " << x << endl;
	}
	return 0;
}

输出示例

1
2
3

分析


ALL RIGHTS RESERVED © 2020 Teddy van Jerry
欢迎转载,转载请注明出处。


See also

Teddy van Jerry 的导航页

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值