简体   繁体   中英

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. 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. I am unsure how to deal with single precision.

@JonathanChan's comments are enlightening, probably more so than anything I might say.

However, I'm not even sure what you mean by validation.

Is "1.0000000000000001" a valid float?

 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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