在AWK浮点计算 [英] floating point calculations in awk

查看:213
本文介绍了在AWK浮点计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与 AWK 在执行浮点计算的行为感到惊讶。这使我对表中的数据计算错误。

  $的awk'BEGIN {打印2.3 / 0.1}
23℃ - 好吧
$ AWK'BEGIN {打印INT(2.3 / 0.1)}
22℃; - 错!$ AWK'BEGIN {打印2.3-2.2 == 0.1}
0℃; - 惊喜!
$ AWK'BEGIN {打印2.3-2.2> 0.1}'< - Din't产生任何输出:(
$ AWK'BEGIN {打印2.3-2.2< 0.1}
1< - 现在完全糊涂了......

有人可以扔光,以什么happing在这里?

修改1

由于指向的的 @fedorqui 的,倒数第二个命令的输出到文件名为 0.1 ,因为重定向操作的(> )。

然后我怎么执行的大于的(> )操作?

解决它也被赋予的 @fedorqui

  $的awk'BEGIN {打印(2.3-2.2> 0.1)}
0℃; - 错!


解决方案

从的手动应该帮助您了解的问题您看到的是:


  

15.1.1.2浮点数是不是抽象的数字


  
  

不像在抽象的意义上的数字(例如你在高中学习什么
  学校或学院算术),存储在计算机上的数字是有限的
  在某些方面。它们不能重新present数字无限数量,
  也不能把他们总是重新present的事情完全一样。尤其是,
  浮点数不能总是重新present值完全相同。这是
  一个例子:

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

这表明一些值可以重新presented准确,而其他
  只是近似。这不是一个错误在awk中,而只是
  的计算机如何重新present数字神器。



一个高度推荐阅读:

的每一台计算机科学家应该知道浮点运算是什么

I am surprised with behaviour of awk while performing floating point calculations. It lead me to wrong calculation on table data.

$ 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 ...

Can somebody throw light as to what's happing here?

EDIT 1

As pointed by @fedorqui, output of second last command goes to file named 0.1 because of redirection operator (>).

Then how am I supposed to perform greater than (>) operation?

Solution to it is also given by @fedorqui

$ awk 'BEGIN {print (2.3-2.2>0.1)}'
0  <-- Wrong!

解决方案

The following section from the manual should help you understand the issue you're observing:

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.


A highly recommended reading:

What every computer scientist should know about floating-point arithmetic

这篇关于在AWK浮点计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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