HDU2899 Strange fuction(牛顿迭代法)

最近刚学完数值分析上的方程求根——牛顿法,所以做几题练习一下。
Problem 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
 题解:此题与2199题解题方法一样,就是2199的变形,都是用牛顿迭代法,也可以用其他方法 ,有时间再补上代码;
与2199的区别就是此题要求导数的根;
用牛顿迭代法解非线性方程f(x)=0,是把非线性方程线性化的一种近似方法。把f(x)在点x0的某邻域内展开成 泰勒 级数 f(x) = f(x0)+(x-x0)f'(x0)+(x-x0)^2*f''(x0)/2! +… ,取其线性部分(即泰勒展开的前两项),并令其等于0,即f(x0)+f'(x0)(x-x0)=0 ,以此作为非线性方程f(x) = 0的近似方程,若f'(x0)≠0,则其解为x1=x0-f(x0)/f'(x0), 这样,得到牛顿迭代法的一个迭代关系式:x(n+1)=x(n)-f(x(n))/f'(x(n))。
注意:
1处:把x1-x0作为结束的条件;
                 2处:k=0(表示返回值是没有方程的根),而若题目在k=0.0出满足题目要求,最好把return 0;改为return -1;
                  3处:需要把0到100内的数都看作选定的初始近似值:
代码实现:
#include<stdio.h>
#include<math.h>
#include<cstring>
#define g(x) 6*x*x*x*x*x*x*x+8*x*x*x*x*x*x+7*x*x*x+5*x*x-y*x

#define f(x) 42*x*x*x*x*x*x+48*x*x*x*x*x+21*x*x+10*x-y
#define f1(x) 42*6*x*x*x*x*x+48*5*x*x*x*x+42*x+10

/*原函数F(x)=g(x),f(x)为F(x)的导数,f1(x)为F(x)的二阶导数;因为在x取0到100之间必有一个解,所以导数f(x)=0,即为方程的最小值,包括端点0和100。*/
using namespace std;
#pragma comment(linker,"/STACK:102400000,102400000")
double y;
double Newton_iteration(double x)
{
int k=1;
while(fabs(f(x))>1e-6)//……1
{
x=x-(f(x))/(f1(x));
k++;
if(k>30)

//超过预定次数,则方法失败;
return -1;
}
return x;
}
int main()
{
//freopen("input.txt","r",stdin);
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lf",&y);
int flag=0;
double z;
for(double x=0.0;x<=100;x++)//……3
{
z=Newton_iteration(x);
if(z<=100.0&&z>=0.0)//……2
{
flag=1;
break;
}
}
if(flag==0)
printf("No solution!\n");//此处对题目没有影响,可以删除
else
printf("%.4lf\n",g(z));
}

return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值