java 泰勒级数_用c中的泰勒级数计算Pi的函数

您的功能有几个错误 . 用“// NOTE:”开头的行看我的评论 .

double get_pi(double accuracy)

{

double estimate_of_pi, latest_term, estimated_error;

int sign = -1;

int n;

estimate_of_pi = 0;

n = 0;

do

{

sign = -sign;

//NOTE: This is an unnecessary line.

estimated_error = 4 * abs(1.0 / (2*n + 1.0)); //equation for error

//NOTE: You have encoded the formula incorrectly.

// The RHS needs to be "sign*4 * (1.0 /(2.0 * n + 1.0))"

// ^^^^ ^

latest_term = 4 * (1.0 *(2.0 * n + 1.0)); //calculation for latest term in series

estimate_of_pi = estimate_of_pi + latest_term; //adding latest term to estimate of pi

n = n + 1; //changing value of n for next run of the loop

}

//NOTE: The comparison is wrong.

// The conditional needs to be "fabs(latest_term) > estimated_error"

// ^^^^ ^^^

while(abs(latest_term)< estimated_error);

//NOTE: You are calling the function again.

// This leads to infinite recursion.

// It needs to be "return estimate_of_pi;"

return get_pi(accuracy);

}

此外, main 中的函数调用是错误的 . 它需要是:

get_pi(0.001)

表示如果该项的绝对值小于0.001,则该函数可以返回 .

这是适用于我的功能的更新版本 .

double get_pi(double accuracy)

{

double estimate_of_pi, latest_term;

int sign = -1;

int n;

estimate_of_pi = 0;

n = 0;

do

{

sign = -sign;

latest_term = sign * 4 * (1.0 /(2.0 * n + 1.0)); //calculation for latest term in series

estimate_of_pi += latest_term; //adding latest term to estimate of pi

++n; //changing value of n for next run of the loop

}

while(fabs(latest_term) > accuracy);

return estimate_of_pi;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值