gpt4 book ai didi

error-handling - 使用int_of_float从float转换时如何处理OCaml中的整数溢出?

转载 作者:行者123 更新时间:2023-12-03 07:40:47 24 4
gpt4 key购买 nike

OCaml 新手在这里。

我试图弄清楚从浮点数转换为整数时如何处理 OCaml 中的整数溢出。

我希望使用 try ... with ...或将其与 nan 进行比较(因为实际上是 has to return nan when float is too large ?),但看起来它不会引发任何错误。
更令人惊讶的是,对于非常大的浮点数 int_of_float 只返回 0 .

utop # 0 = int_of_float 9999999999999999999.0;;
- : bool = true
utop # int_of_float 9999999999999999999.0;;
- : int = 0

如何正确处理 float 到 int 的转换? (更普遍的是 int 溢出?)

最佳答案

确实,OCaml's manual表示float_of_int的“如果参数为 nan 或超出可表示整数的范围,则结果未指定。”

一种可能性是事先检查您的 float 是否适合,并返回一个选项或引发异常,例如

let safe_int_of_float f =
if classify_float f = FP_nan then None
else if f >= float_of_int max_int then None
else if f <= float_of_int min_int then None
else Some (int_of_float f)

关于error-handling - 使用int_of_float从float转换时如何处理OCaml中的整数溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com