简体   繁体   English

将Frege Double转换为Integer

[英]Frege Double to Integer

I would like to be able to convert a large Double to an Integer , but it seems that the Frege Haskell implementation of floor does not yield an Integral type. 我希望能够将大型Double转换为Integer ,但似乎floor的Frege Haskell实现不会产生Integral类型。 Instead, it seems to be implemented to interface with way Java does it, and takes a Floating type to a Double , Floating r => r -> Double . 取而代之的是,它似乎实现了与Java进行交互的方式,并将Floating类型带为DoubleFloating r => r -> Double I could use round , but that rounds rather than truncate (though I might be able to subtract 0.5 and then round). 我可以使用round ,但是可以round而不是截断(尽管我可以减去0.5 然后四舍五入)。 I'd rather work without needing to resort to using Int or Long , which, as wide as the latter is, is still limited in precision. 我宁愿工作而不必求助于使用IntLong ,尽管后者很宽,但精度仍然受到限制。

Any way to go about flooring a floating point type to an arbitrary precision integer type? 有什么办法可以将浮点类型设置为任意精度的整数类型?

This functionality is indeed not available. 此功能确实不可用。 The reason is that Java apparently doesn't offer methods that support it. 原因是Java显然不提供支持它的方法。

What you can do is to convert the (floored) double to a String and converting that to an Integer. 您可以做的是将(floored)double转换为String并将其转换为Integer。

Here is an example: 这是一个例子:

frege> import Prelude.Math(floor)
frege> integerFromDouble d = String.aton ("%.0f".format (floor d))
function integerFromDouble :: Math.Floating a => a -> Integer
frege> integerFromDouble 987654321e20
98765432100000000000000000000

I wonder if there is a more effective method that somehow extracts the mantissa and exponent from a Double and computes the Integer. 我想知道是否有更有效的方法以某种方式从Double中提取尾数和指数并计算Integer。

Note that above function is unsafe because NaN, +Infinity and -Infinity exist: 请注意,上述功能不安全,因为存在NaN,+ Infinity和-Infinity:

frege> integerFromDouble (5/0)
java.lang.NumberFormatException: For input string: "Infinity"

You could either check that separately or replace String.aton with String.integer , which returns 您可以单独检查,也可以将String.aton替换为String.integer ,这将返回

Either NumberFormatException Integer

If you can make sure your computations don't exceed the Long capacity, what you want can be done with: 如果可以确保计算不超过Long容量,则可以使用以下方法完成所需的操作:

round . floor

You could also just call intValue on the Double result after calling floor . 您也可以在调用floor之后在Double结果上调用intValue

http://docs.oracle.com/javase/6/docs/api/java/lang/Number.html#intValue%28%29 http://docs.oracle.com/javase/6/docs/api/java/lang/Number.html#intValue%28%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM