二分法求方程的近似解

这几天好多次都遇到了二分法求方程的解。今天就花了点时间学了一下。其实,说起来也没有什么。高中的时候思想都是有的,只是当时,由于计算繁杂,不作为学习的重点。可是现在不一样了,我们现在,不需要计算,只需要告诉计算机怎么算,来让计算机计算就可以了。所以,现在这种方法也是很受用的吧。

二分法求方程的解的前提是,该函数是单调函数。

思想估计都没有什么问题。关键是代码的问题。

NYOJ 503 解方程为例点击打开链接

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const double eps=1e-6;//eps用来保证数据近似解的精度.当然,得到的解是越精确越好.但是,也就越花费时间.
double ans;

double f(double x){
    return (((8*x-7)*x+2)*x+3)*x+6;
}

double solve(double left,double right){
    double mid;
    while(fabs(right-left)>eps){
        mid=(right+left)/2;
        if(f(mid)==ans) return mid;
        if(f(mid)>ans) right=mid;
        else left=mid;
    }
    return (left+right)/2;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        double  max_val=f(100),min_val=f(0);
        scanf("%lf",&ans);
        if(ans>=min_val&&ans<=max_val)
        printf("%.4lf\n",solve(0,100));
        else printf("No solution!\n");
    }
    return 0;
}

NYOJ 965 Crossed Ladders

这题,也是可以用二分法求方程的近似解。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const double eps=1e-6;
double x,y,c;

double f(double ans){
    double ans1=(y*y-ans*ans);
    double ans2=(x*x-ans*ans);
    return sqrt(ans1*ans2)/(sqrt(ans1)+sqrt(ans2));
}

double solve(double low,double high){
    double mid;
    while(high-low>eps){
        mid=(high+low)/2;
        double temp=f(mid);
//        printf("%.3lf %.3lf %.3lf %.3lf\n",low,high,temp,c);
        if(temp==c) return temp;
        if(temp>c) low=mid;
        else high=mid;
    }
    return (high+low)/2;
}
int main()
{
//    freopen("output.txt","r",stdin);
//    freopen("output1.txt","w",stdout);
    while(scanf("%lf%lf%lf",&x,&y,&c)!=EOF)
    {
        double low=min(x,y);
        printf("%.3lf\n",solve(0,low));
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值