Is there a function for integer exponentiation in OCaml? ** is only for floats. Although it seems to be mostly accurate, isn't there a possibility of precision errors, something like 2. ** 3. = 8. returning false sometimes? Is there a library function for integer exponentiation? I could write my own, but efficiency concerns come into that, and also I'd be surprised if there isn't such a function already.
相关问题
- Do the Java Integer and Double objects have unnece
- Writing an interpreter in OCaml [closed]
- Is it possible to distinguish Bool and Int in Swif
- Using Core.Std.List.fold_left without label
- See if key exists in a String Map
Not in the standard library. But you can easily write one yourself (using exponentiation by squaring to be fast), or reuse an extended library that provides this. In Batteries, it is Int.pow.
Below is a proposed implementation:
If there is a risk of overflow because you're manipulating very big numbers, you should probably use a big-integer library such as Zarith, which provides all sorts of exponentiation functions.
(You may need the "modular exponentiation", computing
(a^n) mod p
; this can be done in a way that avoids overflows by applying the mod in the intermediary computations, for example in the functionpow
above.)Regarding the floating-point part of your question: OCaml calls the underlying system's
pow()
function. Floating-point exponentiation is a difficult function to implement, but it only needs to be faithful (that is, accurate to one Unit in the Last Place) to make2. ** 3. = 8.
evaluate totrue
, because8.0
is the onlyfloat
within one ULP of the mathematically correct result 8.All math libraries should(*) be faithful, so you should not have to worry about this particular example. But not all of them actually are, so you are right to worry.
A better reason to worry would be, if you are using 63-bit integers or wider, that the arguments or the result of the exponentiation cannot be represented exactly as OCaml floats (actually IEEE 754 double-precision numbers that cannot represent
9_007_199_254_740_993
or 253 + 1). In this case, floating-point exponentiation is a bad substitute for integer exponentiation, not because of a weakness in a particular implementation, but because it is not designed to represent exactly integers that big.(*) Another fun reference to read on this subject is “A Logarithm Too Clever by Half” by William Kahan.
A simpler formulation of the solution above:
pow' a x n
computesa
timesx
to then
.Here's another implementation which uses exponentiation by squaring (like the one provided by @gasche), but this one is tail-recursive