双精度时,浮点值传递为double [英] Double Precision when a float value is passed in double

查看:168
本文介绍了双精度时,浮点值传递为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有双精度的问题。当一个浮点值传递给double时,我得到一些不同的结果。例如,

I have on question regarding double precision.When a float value is passed into double then I get some different result. For e.g.

float f= 54.23f;
double d1 = f;
System.out.println(d1);

输出为54.22999954223633。有人可以解释这个行为背后的原因。是否为双精度值,以十进制精度为14位。

The output is 54.22999954223633. Can someone explain the reason behind this behaviour. Is it like double defaults to 14 places of decimal precision.

推荐答案

相同的值以 double 此处,并查看链接的文档,以获得更精确的定义)。

The same value is printed differently for float and double because the Java specification requires printing as many digits as needed to distinguish the value from adjacent representable values in the same type (per my answer here, and see the linked documentation for more precision in the definition).

由于 float 具有较少的位来表示值,因此数值较少,它们之间的间隔更广泛,您不需要同样多的数字来区分它们。当您将值放入 double 并打印时,Java规则要求打印更多的数字,以使该值与附近的 double 值。 println 函数不知道该值最初来自 float ,并不包含尽可能多的信息成为 double

Since float has fewer bits to represent values, and hence fewer values, they are spaced more widely apart, and you do not need as many digits to distinguish them. When you put the value into a double and print it, the Java rules require that more digits be printed so that the value is distinguished from nearby double values. The println function does not know that the value originally came from a float and does not contain as much information as can fit into a double.

54.23f 正好是54.229999542236328125 (十六进制,0x1.b1d70ap + 5)。刚刚低于此处的 float 值为54.2299957275390625(0x1.b1d708p + 5)和54.23000335693359375(0x1.b1d70cp + 5)。如您所见,打印54.229999会将值与54.229995 ...和54.23 ...区分开来。但是,刚刚低于 54.23f double 值分别为54.22999954223632101957264239899814128875732421875和54.22999954223633523042735760100185871124267578125。要区分该值,您需要54.22999954223633。

54.23f is exactly 54.229999542236328125 (in hexadecimal, 0x1.b1d70ap+5). The float values just below and just above this are 54.2299957275390625 (0x1.b1d708p+5) and 54.23000335693359375 (0x1.b1d70cp+5). As you can see, printing "54.229999" would distinguish the value from 54.229995… and from 54.23…. However, the double values just below and just above 54.23f are 54.22999954223632101957264239899814128875732421875 and 54.22999954223633523042735760100185871124267578125. To distinguish the value, you need "54.22999954223633".

这篇关于双精度时,浮点值传递为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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