JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.77k stars 5.49k forks source link

Increase accuracy of two-argument `log` function #46926

Open eschnett opened 2 years ago

eschnett commented 2 years ago

The function log2 is generally (very slightly) more accurate (and also slightly faster) than log, since IEEE floating-point numbers are stored in a base-2 representation.

Julia define the generic (two-argument) log as log(x, y) = log(y) / log(x). This could be improved (to be slightly faster and slightly more accurate) by changing this to log(x, y) = log2(y) / log2(x).

For example:

julia> log(1000000) / log(100)
2.9999999999999996

julia> log2(1000000) / log2(100)
3.0
DilumAluthge commented 2 years ago

Are there any downsides to making this switch?

oscardssmith commented 2 years ago

IMO, this is a very reasonable switch to make. The main reason it is the way it is is likely that for a couple years, our log was better than our log2 since no one had updated the log2 version.

eschnett commented 2 years ago

I notice that ^ uses exp2 and log2 in its implementation.

oscardssmith commented 2 years ago

well for Float32 it does. For Float64 it uses log and exp since the in extended precision, it is a benefit to have exact coefficients in the polynomial.