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

标签 error-handling ocaml

这里是 OCaml 新手。

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

我希望使用 try ... with ... 或将其与 nan 进行比较(因为实际上 has to return nan when float is too large ?),但看起来确实如此不抛出任何错误。 更令人惊讶的是,对于非常大的 float 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 从浮点转换时如何处理 OCaml 中的整数溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871692/

相关文章:

tdd - 如何进行测试驱动开发?

error-handling - 使用批处理模式处理OData异常

ocaml - 如何安装支持 lwt 的 Cohttp?

tree - 有没有更好的方法来构造这样的优先级队列?

php - 删除所有不需要的字符

list - 在 ocaml 中定义一棵树 + 指向其子树的指针

ocaml - 是否有 OCaml 的增量构建之类的东西?

sql - 无法连接到SQL

error-handling - “This XML file does not appear to have any style information”

.net分层设计: return error code to forms indicating which controls have an error