gpt4 book ai didi

floating-point - 为什么浮点运算在某些语言中显示不同?

转载 作者:行者123 更新时间:2023-12-03 13:24:29 26 4
gpt4 key购买 nike

我读过这些:

  • Why Are Floating Point Numbers Inaccurate?
  • http://floating-point-gui.de/

  • 他们解释“如何”。我想知道为什么这些语言会有所不同。给定相同的输入,我期望得到类似的结果。

    测试.js
    #!/usr/bin/env node

    var nine = 9.0;
    var pointOhOhOne = 0.001;
    var result = nine * pointOhOhOne;
    console.log(result);

    测试.java
    public class test {

    public static void main(String[] argv) {
    double nine = 9.0d;
    double pointOhOhOne = 0.001d;
    double result = nine * pointOhOhOne;
    System.out.println(result);
    }

    }

    测试.c
    #include "stdio.h"

    int main() {
    double nine = 9.0;
    double pointOhOhOne = 0.001;
    double result = nine * pointOhOhOne;
    printf("%f", result);
    }

    测试.rb
    #!/usr/bin/env ruby

    nine = 9.0
    pointOhOhOne = 0.001
    result = nine * pointOhOhOne

    print result

    测试.py
    #!/usr/bin/env python

    nine = 9.0
    pointOhOhOne = 0.001
    result = nine * pointOhOhOne

    print result

    结果:
    ruby     0.009000000000000001
    python 0.009
    node 0.009000000000000001
    java 0.009000000000000001
    c 0.009000

    要点: https://gist.github.com/reklis/6694ad5fb01991a79a1a

    最佳答案

    在我的系统上的 C 中:

    printf("%.18f\n", result);

    0.009000000000000001

    在我系统上的 Python 中:
    print("%.18f" % result)

    0.009000000000000001

    C 或 Python 与其他语言一样,默认使用其打印函数限制十进制数字的数量。

    关于floating-point - 为什么浮点运算在某些语言中显示不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26168930/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com