gpt4 book ai didi

awk - awk 中的浮点计算

转载 作者:行者123 更新时间:2023-12-04 17:35:44 30 4
gpt4 key购买 nike

我对 awk 的行为感到惊讶表演时浮点数 计算。它导致我对表格数据进行错误计算。

$ awk 'BEGIN {print 2.3/0.1}'
23 <-- Ok
$ awk 'BEGIN {print int(2.3/0.1)}'
22 <-- Wrong!

$ awk 'BEGIN {print 2.3-2.2==0.1}'
0 <-- Surprise!
$ awk 'BEGIN {print 2.3-2.2>0.1}' <-- Din't produce any output :(
$ awk 'BEGIN {print 2.3-2.2<0.1}'
1 <-- Totally confused now ...

有人可以了解这里发生了什么吗?

编辑 1

正如@fedorqui 所指出的,倒数第二个命令的输出到名为 的文件中0.1 由于重定向运算符( > )。

那么我应该如何执行大于 ( > ) 操作?

@fedorqui 也给出了解决方案
$ awk 'BEGIN {print (2.3-2.2>0.1)}'
0 <-- Wrong!

最佳答案

以下部分来自manual应该可以帮助您了解您正在观察的问题:

15.1.1.2 Floating Point Numbers Are Not Abstract Numbers

Unlike numbers in the abstract sense (such as what you studied in high school or college arithmetic), numbers stored in computers are limited in certain ways. They cannot represent an infinite number of digits, nor can they always represent things exactly. In particular, floating-point numbers cannot always represent values exactly. Here is an example:

 $ awk '{ printf("%010d\n", $1 * 100) }'
515.79
-| 0000051579
515.80
-| 0000051579
515.81
-| 0000051580
515.82
-| 0000051582
Ctrl-d

This shows that some values can be represented exactly, whereas others are only approximated. This is not a “bug” in awk, but simply an artifact of how computers represent numbers.



强烈推荐阅读:

What every computer scientist should know about floating-point arithmetic

关于awk - awk 中的浮点计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19656446/

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