计算e ^ x而不使用任何函数 [英] Calculating e^x without using any functions

查看:275
本文介绍了计算e ^ x而不使用任何函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应该使用这种公式计算e ^ x:



e ^ x = 1 +(x ^ 1/1!)+ 2/2!)......



我有这样的代码:

  while(result> = 1.0E-20)
{
power = power * input;
factorial = factorial * counter;
result = power / factorial;
eValue + = result;
counter ++;
iterations ++;我现在的问题是,因为factorial是一个类型long long,我可以''''' t真正存储一个大于20的数字!所以发生的是当程序输出有趣的数字,当它到达那个点。



正确的解决方案可以有一个X值至多709,所以e ^ 709应输出:8.21840746155e + 307



程序是用C ++编写的。

解决方案

p>两者x ^ n和n!快速增长与n(指数和超分别)和将很快溢出您使用的任何数据类型。另一方面,x ^ n / n! (最终),你可以停止当它的小。也就是说,使用x ^(n + 1)/(n + 1)!的事实。 =(x ^ n / n!)*(x /(n + 1))。像这样:

  term = 1.0; 
for(n = 1; term> = 1.0E-10; n ++)
{
eValue + = term;
term = term * x / n;
}

(直接在此框中键入代码,但我希望它能工作。



编辑:请注意,术语x ^ n / n!是,对于大x,增加一段时间,然后减少。对于x = 709,它在上升到0之前上升到〜1e + 306,这正好在 double 可以处理的限度上( double 的范围是〜1e308和 term * x 将其推回),但 long double 工作正常。当然,您的最终结果 e x 大于任何条件,因此假设您使用的数据类型足够大,可以容纳结果,您将罚款。



(对于x = 709,如果使用<$ c,你可以使用 double $ c> term = term / n * x ,但它不适用于710.)


We are supposed to calculate e^x using this kind of formula:

e^x = 1 + (x ^ 1 / 1!) + (x ^ 2 / 2!) ......

I have this code so far:

while (result >= 1.0E-20 )
{
    power = power * input;
    factorial = factorial * counter;
    result = power / factorial;
    eValue += result;
    counter++;
    iterations++;
}

My problem now is that since factorial is of type long long, I can't really store a number greater than 20! so what happens is that the program outputs funny numbers when it reaches that point ..

The correct solution can have an X value of at most 709 so e^709 should output: 8.21840746155e+307

The program is written in C++.

解决方案

Both x^n and n! quickly grow large with n (exponentially and superexponentially respectively) and will soon overflow any data type you use. On the other hand, x^n/n! goes down (eventually) and you can stop when it's small. That is, use the fact that x^(n+1)/(n+1)! = (x^n/n!) * (x/(n+1)). Like this, say:

term = 1.0;
for(n=1; term >= 1.0E-10; n++)
{
    eValue += term;
    term = term * x / n;
}

(Code typed directly into this box, but I expect it should work.)

Edit: Note that the term x^n/n! is, for large x, increasing for a while and then decreasing. For x=709, it goes up to ~1e+306 before decreasing to 0, which is just at the limits of what double can handle (double's range is ~1e308 and term*x pushes it over), but long double works fine. Of course, your final result ex is larger than any of the terms, so assuming you're using a data type big enough to accommodate the result, you'll be fine.

(For x=709, you can get away with using just double if you use term = term / n * x, but it doesn't work for 710.)

这篇关于计算e ^ x而不使用任何函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆