C程序不能正确添加浮点数 [英] C program not adding float correctly

查看:239
本文介绍了C程序不能正确添加浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  float * mutate(float * organism){
int一世;
浮点数= 1;
static float newOrg [INPUTS] = {0};

(i = 0; i if(rand()%2 == 0){
sign = 1;
} else {
sign = -1;
}
float temp =(organism [i] + sign);
printf(bf:%f af:%f diff:%f sign:%f sign2:%f temp:%f\\\
\\\

organism [i],(organism (有机体[i] +符号) - 有机体[i],
符号,符号+符号,温度);
newOrg [i] =有机体[i] +符号;
}

return newOrg;

sign 是不是0,前两个%f s是相同的,第三个是0,也把总和放在一个变量中并没有帮助。这让我感到困惑!

输出:

  bf :117810016.000000 af:117810016.000000 diff:0.000000 sign:1.000000 sign2:2.000000 temp:117810016.000000 


解决方案 有限精度 float
$ b

一个典型的 code>只能表示大约2 <32>个不同的数字。 117,810,016.0和1.0是其中两个。 117,810,017.0不是。因此, 117810016.0 + 1.0 的C总和得到了 117810016.0 的最佳答案。
$ b

使用像 double 这样的更高精度的类型往往会扩展+1精确数学的范围,但即使这样也不够精确(通常约为9.0 * 10e 15或2 53)。

如果代码要保留使用 float ,建议限制有机体[i] 为包含范围的值或±8,388,608.0(2 23

也许可以使用整数类型来完成这个任务,比如 long long


I have a method that looks like this:

float * mutate(float* organism){   
    int i;
    float sign = 1;
    static float newOrg[INPUTS] = {0};

    for (i = 0;i<INPUTS;i++){
        if (rand() % 2 == 0) {
            sign = 1;
        } else {
            sign = -1;
        }
        float temp = (organism[i] + sign);
        printf("bf: %f af: %f diff: %f sign: %f sign2: %f temp: %f\n\n",
            organism[i], (organism[i] + sign), (organism[i] + sign)-organism[i],
            sign, sign+sign, temp);
        newOrg[i] = organism[i] + sign;
    }

    return newOrg;
}

When sign is not 0 the first two "%f"s are the same and the 3rd is 0, also putting the sum in a variable didn't help. This is baffling me! I can post full code if needed.

Output:

bf: 117810016.000000 af: 117810016.000000 diff: 0.000000 sign: 1.000000 sign2: 2.000000 temp: 117810016.000000

解决方案

Finite precision of float.

A typical float can only represent about 232 different numbers. 117,810,016.0 and 1.0 are two of them. 117,810,017.0 is not. So the C sum of 117810016.0 + 1.0 results in the "best" answer of 117810016.0.

Using a higher precision type like double often will extend the range of +1 exact math, but even that will not be exact with large enough values (typically about 9.0*10e15 or 253).

If code is to retain using float, suggest limiting organism[i] to values to the inclusive range or ±8,388,608.0 (223).

Perhaps can code simply use integer types for this task like long long.

这篇关于C程序不能正确添加浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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