Can you solve this equation?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16850 Accepted Submission(s): 7491
Problem Description
Now,given the equation 8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.
Input
The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);
Output
For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.
Sample Input
2
100
-4
Sample Output
1.6152
No solution!
题目给你一个y,让你判断它的解是否在0~100内,开始没想到做法啊,其实做过了,还是不太熟悉二分
二分代码:
/*
以为可以用高中的数学公式推出来呢,看样子是不能了,开始想到二分,
但是对小数操作不怎么会,就弃了,看了别人写的觉得就是自己不熟练二分啊
*/
#include
#include
#include
#include
#include
using namespace std;
const double zero = 1e-6;
double solve(double x)
{
return 8*x*x*x*x + 7*x*x*x + 2*x*x + 3*x + 6;
}
int main()
{
int t;
cin >> t;
double y;
while(t--)
{
scanf("%lf",&y);
if(solve(0)>y || y>solve(100))
{
printf("No solution!
");
}
else
{
//用二分的方法,可谓精妙
double l = 0.0,r = 100.0,mid = (l+r)/2;
while(fabs(solve(mid) - y) > zero)//”相等“
{
if(solve(mid)>y)
r = mid - 1;
else
l = mid + 1;
mid = (l+r)/2;
}
printf("%.4f
",mid);
}
}
return 0;
}
因为是求一个高次方程的解,大部分高次方程都不存在求根公式,用牛顿迭代法可以求解的近似值,但是每次迭代的结果都不是精确值。此处又要扯上极限了,连续函数迭代求得的解是会收敛于零点的,所以最终结果就极其接近真实解了。具体解释见牛顿迭代法
公式
牛顿迭代法代码:
#include
#include
#include
#include
#include
using namespace std;
const double zero = 1e-6;
double y;
double solve(double x)
{
return 8*x*x*x*x + 7*x*x*x + 2*x*x + 3*x + 6;
}
double der(double x)//上式求导
{
return 32*x*x*x + 21*x*x + 4*x + 3;
}
double NM(double x)
{
int cnt = 1;
while(fabs(solve(x) - y) > zero)
{
x = x - (solve(x)-y)/der(x);//牛顿迭代法
if(++cnt > 30)
return 0;//break;
}
return x;
}
int main()
{
int t;
cin >> t;
while(t--)
{
scanf("%lf",&y);
bool flag = false;
double k;
for(double i = 0.0;i < 100;i++)
{
k = NM(i);
if(k && k >= 0.0 && k <= 100.0)
{
flag = true;
break;
}
}
if(flag)
printf("%.4f
",k);
else
printf("No solution!
");
}
return 0;
}
代码参考自
静涛,退出方式待研究