Can you solve this equation?Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 8567 Accepted Submission(s): 3948
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
Sample Output
|
思路:
设f(x)=8*x^4+7*x^3+2*x^2+3*x+6 ,定义域为[0,100]
求导可证明f(x)在区间上单调增,所以在 f(0)<=f(x)<=f(100) ,
所以二分查找Y,当然先判断下Y是否满足:f(0)<=Y<=f(100)
上代码:
递归版:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
double Equation(double x)
{
return 8*pow(x,4)+7*pow(x,3)+2*x*x+3*x+6;
}
double BiSearch(double Y,double left,double right)
{
double mid=(left+right)/2;
if(right-left>=10e-7) //如果是-6就错了。。。卡精度的呀。。。为什么!!!
{
if(Equation(mid)==Y)
return mid;
if(Equation(mid)>Y)
return BiSearch(Y,left,mid);
if(Equation(mid)<Y)
return BiSearch(Y,mid,right);
}
return mid;
}
int main()
{
double x,Y;
int cases;
scanf("%d",&cases);
while(cases--)
{
scanf("%lf",&Y);
if(Y<Equation(0) || Y>Equation(100))
printf("No solution!\n");
else
printf("%.4lf\n",BiSearch(Y,0,100));
}
return 0;
}
非递归版:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
double Equation(double x)
{
return 8*pow(x,4)+7*pow(x,3)+2*x*x+3*x+6;
}
int main()
{
double x,Y;
int cases;
scanf("%d",&cases);
while(cases--)
{
scanf("%lf",&Y);
if(Y<Equation(0) || Y>Equation(100))
printf("No solution!\n");
else
{
double left=0,right=100,mid;
while(right-left>10e-12) //还是卡精度,干脆就严格点。。。
{
mid=(left+right)/2;
if(Equation(mid)>Y)
right=mid;
else
left=mid;
}
printf("%.4lf\n",mid);
}
}
return 0;
}
怎么能保证不在精度上出问题???SOS!!!