Search code examples
ocamlinfinity

Represent infinity in the Num module


In the Num module, it is said :

Numbers (type num) are arbitrary-precision rational numbers, plus the special elements 1/0 (infinity) and 0/0 (undefined).

I expected to find this infinity but can't find it. I guessed, then, that I could create it by hand :

let infinity = let one = Int 1 and zero = Int 0 in one // zero

But bum :

Exception: Failure "create_ratio infinite or undefined rational number".

So, ok, there is this val infinity : float in Pervasives, let's find a num_from_float. Oh, there's no such function...

Well, does anyone know how to represent positive and negative infinity with Num ?


Solution

  • By default, special numbers are disabled. This behavior can be controlled with the Arith_status module. For example, to allow zero denominators, use the following:

    Arith_status.set_error_when_null_denominator false
    

    Once the flag is set, your infinity definition works fine:

    let infinity = let one = Int 1 and zero = Int 0 in one // zero;;
    val infinity : Num.num = <num 1/0>
    float_of_num infinity;;
    - : float = infinity