您的位置:首页 > 其它

Can you solve this equation?(简单二分)

2015-03-24 21:23 369 查看
没有分析函数的单调性,但是直觉告诉我这是单调函数,至于单增还是单减就没有判断了,直接二分。

#include<iostream>
#include<cstdlib>
#include<cstdio>
#define long long LL
const double dev = 1E-9;
//const double dev2= 1E-5;
using namespace std;

double dabs(double a)
{
return a>0? a : -a;
}

double fun(double x,double y)<span style="white-space:pre">//构造方程为一个函数,如果函数值很接近于0,则x就是方程的解
{
return 8*x*x*x*x + 7*x*x*x + 2*x*x + 3*x + 6 - y;
}

int main()
{
int t;
cin>>t;
while(t--)
{
int flag = 0;
double y;
cin>>y;
double low=0,high=100,mid=50;
if(fun(0,y)/fun(100,y)>0)          //高中学过的二分法,怕溢出,用的除法
cout<<"No solution!"<<endl,flag = 1;
else
while(dabs(low-high)>dev)        //控制精度
{
if(fun(low,y)/fun(mid,y) < 0)          //如果解在这个范围内
{
high = mid;           //更改区间
mid = (low+high)/2;
}
else          //如果不在这个范围内,换一种方式更改解所在的区间
{
low = mid;
mid = (low+high)/2;
}
}
if(flag == 0)printf("%.4lf\n",mid);
}
return EXIT_SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: