二分或三分查找:C - Strange fuction 解题报告

Strange fuction

Description

Now, here is a fuction: 
  F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x (0 <= x <=100) 
Can you find the minimum value when x is between 0 and 100.

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 only one real numbers Y.(0 < Y <1e10)

Output

Just the minimum value (accurate up to 4 decimal places),when x is between 0 and 100.

Sample Input

2
100
200

Sample Output

-74.4291
-178.8534

题意:给定Y,求当0<=x<=100时f(x)的最小值。

解题思路:首先看这个函数并没有单调性可言,但是我们对其求导之后发现

f'(x)=42x^6+48x^5+21x^2+10^x-y.

容易发现 f'(x) 在[0,100]上是一个单调递增的函数,那么问题就简单了,如果f'(x)在[0,100]上存在零点x0,那么f(x0)必然就是所求的最小值,怎么求零点?二分查找啊~

如果不存在零点,也就是f'(100)<0或者f'(0)>0的情况,意味着f(x)单调递减或者单调递增,那么直接输出f(100)或f(0)就可以了。

#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <cstdio>
using namespace std;

const double EPS=1e-5;

double y;

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

double f2(double x) //f(x)求导
{
    return 42*pow(x,6)+48*pow(x,5)+21*pow(x,2)+10*x;
}

double bs()
{
    double lo=0,hi=100;
    double mi;
    while(1)
    {
        mi=(lo+hi)/2.0;//浮点数问题就别移位运算了
        if(fabs(f2(mi)-y)<EPS) return mi;
        else if(f2(mi)>y)
            hi=mi;
        else
            lo=mi;
    }
    return -1;
}


int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>y;
        if(f2(100)-y<0)
            printf("%.4f\n",f(100));
        else if(f2(0)-y>0)
            printf("%.4f\n",f(0));
        else
            printf("%.4f\n",f(bs()));

    }
    return 0;
}

</pre><p></p><p><span style="font-family:SimHei;font-size:18px;">以上说的是使用二分查找的方法,但是这道题也可以使用三分。</span></p><p><span style="font-family:SimHei;font-size:18px;">可以用二分的方法AC之后再试一下用三分解这道题,可以作为练习三分的入门题。</span></p><p><span style="font-family:SimHei;font-size:18px;">用三分查找可以直接求得单峰函数的极值</span></p><p><span style="font-family:SimHei;font-size:18px;"></span><pre name="code" class="cpp">#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;

const double EPS=1e-6;
double y;

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

double ts()
{
    double l=0,r=100,mid,mmid;
    mid=(l+r)/2.0;
    mmid=(mid+r)/2.0;
    while(fabs(mid-mmid)>EPS)
    {
        mid=(l+r)/2.0;
        mmid=(mid+r)/2.0;
        if(f(mid)<f(mmid))
            r=mmid;
        else
            l=mid;
    }
    return f(mid);
}



int main()
{
    int repeat;
    cin>>repeat;
    while(repeat--)
    {
        cin>>y;
        printf("%.4lf\n",ts());
    }
    return 0;
}









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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值