铸造双到浮动后不正确的值 [英] incorrect value after casting double to a float

查看:122
本文介绍了铸造双到浮动后不正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些C code进行高precision算术由GCC编译(海湾合作委员会(GCC)4.4.4 20100726(红帽4.4.4-13))。计算的最终结果是双其中有622.07999995861189.I的价值正在铸造双为float。

I have some C code performing high precision arithmetic compiled by gcc(gcc (GCC) 4.4.4 20100726 (Red Hat 4.4.4-13)).The final result of the calculation is a double which has a value of 622.07999995861189.I am casting the double to a float.

frequency_value =(浮点)current_freq;

frequency_value = (float)current_freq;

其中current_freq是一张双人床和frequency_value是frequency_value的投后float.The值622.080017.I期望的值是622.079956由

where current_freq is a double and frequency_value is a float.The value of frequency_value after the cast is 622.080017.I would expect the value to be 622.079956 as calculated in gdb by

(GDB)P(浮动)current_freq
$ 1 = 622.079956

(gdb) p (float)current_freq $1 = 622.079956

任何人都可以解释,通过gcc和gdb的计算之间的数值相差较大。

Can anyone explain the large difference in values between that calculated by gcc and gdb.

推荐答案

一个浮动有precision比双少得多;你失去了大约一半的数字。所以,充其量你会看到622.0799部分(四舍五入至622.0800)。您所看到的差异可能是由使用的舍入模式造成的。

A float has much less precision than a double; you lose about half the digits. So at best you'd be seeing the 622.0799 portion (rounded up to 622.0800). The difference you see is probably caused by the rounding mode in use.

下面是实际的数字:


  • 由于采用双:622.0799999586118929073563776910305023193359375

  • 为float:622.08001708984375(内部重新presentation:1142654239)

  • 立即─preceding浮动:622.0799560546875(内部重新presentation:1142654238)

在内部重新presentations是使用Java的 Float.floatToIntBits 生成的值。您还可以使用 Float.intBitsToFloat 来得到一个浮点数。

The internal representations are values generated using Java's Float.floatToIntBits. You can also use Float.intBitsToFloat to get back a floating-point number.

这篇关于铸造双到浮动后不正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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