HDU—2199—Can you solve this equation?—【二分】【精度控制】

本文介绍了一个特定多项式方程的数值解法,通过二分查找算法在指定区间内精确求解给定方程的实数根,并提供了两种实现方式:递归版与非递归版。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
2 100 -4
 

Sample Output
1.6152 No solution!
 


思路:

设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!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值