首页 文章

计算sinh的泰勒级数

提问于
浏览
2

该函数使用Taylor系列中的以下开发计算 sinh(x) 的值:

sinh

我想计算sinh(3)= 10.01787的值,但函数输出9.我也得到这个警告:

1> main.c(24):警告C4244:'function':从'double'转换为'int',可能会丢失数据

这是我的代码:

int fattoriale(int n)
{
    int risultato = 1;
    if (n == 0) 
    {
        return 1;
    }
    for (int i = 1; i < n + 1; i++) 
    {
        risultato = risultato * i;
    }
    return risultato;
}

int esponenziale(int base, int esponente) 
{
    int risultato = 1;
    for (int i = 0; i < esponente; i++) 
    {
        risultato = risultato * base;
    }
    return risultato;
}

double seno_iperbolico(double x) 
{
    double risultato = 0, check = -1;
    for (int n = 0; check != risultato; n++)
    {
        check = risultato;
        risultato = risultato + (((esponenziale(x, ((2 * n) + 1))) / (fattoriale((2 * n) + 1))));
    }
    return risultato;
}

int main(void) 
{
    double numero = 1;
    double risultato = seno_iperbolico(numero);
}

请帮我修复这个程序 .

2 回答

  • 4

    编译器警告你这种数据丢失实际上非常棒 .
    你看,当你打电话给这个时:

    esponenziale(x, ((2 * n) + 1))
    

    由于您将 doublex )转换为 int ,因此基本上会失去准确性 . 这是因为 esponenziale 的签名是 int esponenziale(int base, int esponente) .

    将它更改为 double esponenziale(double base, int esponente)risultato 也应该是 double ,因为您从函数返回它并使用/执行数学运算 .

    请记住,将 doubleint 分开会给你一个 double .

    编辑:根据ringø的评论,看看它是如何解决你的问题,你也应该设置 double fattoriale(int n) 并在 double risultato = 1; 内 .

  • 3
    • 您正在失去精确度,因为许多术语将是小数量 . 使用 int 将破坏小数部分 . 根据需要将 int 类型替换为 double 类型 .

    • 你的阶乘函数会因 n 的惊人小值而溢出 . 对于16位 intn 的最大值为7,对于32位,它为's 12 and for 64 bit it' s 19.溢出 signed 整数类型的行为未定义 . 如果您的编译器支持,您可以使用 unsigned long longuint128_t . 这会给你带来更多的时间 . 但是无论如何你都要转换成 double ,你也可以从一开始就使用 double . 请注意,IEEE764浮点双精度将达到171无穷大!

    • 请确保 sinh 的Maclaurin展开的收敛半径对于 x 的任何值都是无限的 . 所以 x 的任何值都可以工作,尽管收敛可能很慢 . 见http://math.cmu.edu/~bkell/21122-2011f/sinh-maclaurin.pdf .

相关问题