如何获得体系结构所支持的最小的下一个或上一个可能的double值? [英] How to get the smallest next or previous possible double value supported by the architecture?

查看:138
本文介绍了如何获得体系结构所支持的最小的下一个或上一个可能的double值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个 double 变量 d 。有没有办法获得CPU架构支持的下一个或上一个值?作为一个简单的例子,如果这个值是10.1245125,架构的精度被固定为7位小数,那么下一个值就是10.1245126,而前一个值就是是10.1245124。

显然在浮点体系结构中,这并不那么简单。我怎么能够实现这个(在Java中)?实际上,IEEE 754浮点架构使得这个变得简单:感谢这个标准,这个函数在几乎所有的语言中都被称为 nextafter 它和这个一致性让我可以用对Java的熟悉程度来回答你的问题:
$ b


java.lang.Math.nextAfter(double start,double direction)在第二个参数的方向上返回与第一个参数相邻的浮点数。


< blockquote>

请记住,-infinity和+ infinity是浮点值,这些值可以方便地给出方向(第二个参数)。不要写出像 Math.nextAfter(x,x + 1)这样的常见错误,它只有在1大于 ULP of x



任何编写上述内容的人都可以使用 Math.nextAfter(x,Double.POSITIVE_INFINITY)来保存一个加法运算,并且适用于所有 x


Lets say I have a double variable d. Is there a way to get the next or previous value that is supported by the CPU architecture.

As a trivial example, if the value was 10.1245125 and the precision of the architecture was fixed to 7 decimal places, then the next value would be 10.1245126 and the previous value would be 10.1245124.

Obviously on floating-point architectures this is not that simple. How would I be able to achieve this (in Java)?

解决方案

Actually, an IEEE 754 floating-point architecture makes this easy: thanks to the standard, the function is called nextafter in nearly all languages that support it, and this uniformity allowed me to write an answer to your question with very little familiarity with Java:

The java.lang.Math.nextAfter(double start, double direction) returns the floating-point number adjacent to the first argument in the direction of the second argument.

Remember that -infinity and +infinity are floating-point values, and these values are convenient to give the direction (second argument). Do not make the common mistake of writing something like Math.nextAfter(x, x+1), which only works as long as 1 is greater than the ULP of x.

Anyone who writes the above probably means instead Math.nextAfter(x, Double.POSITIVE_INFINITY), which saves an addition and works for all values of x.

这篇关于如何获得体系结构所支持的最小的下一个或上一个可能的double值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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