[英]IEEE 64 and 32 bit float validation in OCaml
I have a string matching the following regex \\-?[0-9]*\\.[0-9]+
which supposedly represents a IEEE floating point number. 我有一个与以下正则表达式
\\-?[0-9]*\\.[0-9]+
相匹配的字符串,该表达式可能表示IEEE浮点数。 It could be single or double precision and I know the type in advance. 它可以是单精度或双精度,我事先知道类型。 I need to check if it could be interpreted as a valid value in given precission.
我需要检查在给定的精度下是否可以将其解释为有效值。 Something like:
就像是:
val is_valid_float: string -> bool
val is_valid_double: string -> bool
For double precision numbers, I can just parse it using float_of_string
and catch the exception. 对于双精度数字,我可以使用
float_of_string
解析它并捕获异常。 I am unsure how to deal with single precision. 我不确定如何处理单精度。
@JonathanChan's comments are enlightening, probably more so than anything I might say. @JonathanChan的评论很有启发性,可能比我能说的要多。
However, I'm not even sure what you mean by validation. 但是,我什至不知道验证的含义。
Is "1.0000000000000001" a valid float? “ 1.0000000000000001”是有效的浮点数吗?
val f : string = "1.0000000000000001"
# float_of_string f;;
- : float = 1.
#
There's no exception to indicate that this number can't be represented as distinct from 1.0. 毫无例外地表示此数字不能表示为不同于1.0。
If you ignore issues of precision, it might not be difficult to test against the representable range just as a string operation. 如果您忽略精度问题,那么就可以像字符串操作一样在可表示范围内进行测试,这可能并不困难。
As @JonathanChan points out, the best answer probably depends on how sure you need to be (and what you want to be sure of, exactly). 正如@JonathanChan指出的那样,最好的答案可能取决于您需要被确保的程度(以及您想要确定的确切程度)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.