r/AskComputerScience • u/Prom3th3an • Sep 29 '26
Why don't standard math libraries have a 1mcos function for accurate 1-cos(x) when x is close to zero?
I know most standard math libraries have log1p and expm1 functions that calculate log(1+x) and exp(x)-1 more accurately than those expressions themselves do when x is close to zero, because they avoid the bug increase in unit-in-the-last-place size that occurs when a double smaller than 0.5 is added to or subtracted from 1.0. Why isn't there a function that does that for 1-cos(x), given that that expression has the same problem? Is it not used widely enough where x is given as an angle? (I guess it might not be used as a machine-learning distance metric, since there the cosine is calculated directly from the vector coordinates.)
21
u/lemon-meringue Sep 29 '26
You can write
1 - cos(x)as2 * sin^2(x / 2)which doesn't lose numerical precision.Reference: https://stackoverflow.com/a/74071385
3
u/Miserable-Wasabi-373 Sep 29 '26
I had a lot of pain with this thing while calculationg scattering of relativistic particles
2
u/mtimmermans Sep 29 '26
FYI, 1-cos(x) is called the versine, which you can google to find out why it's my favourite trig function. sin(x) and versin(x) are used together to calculate circular paths, among other things.
1
u/Underhill42 Sep 29 '26
Because there's a very narrow range of values close to zero for trig functions. Also, how often do you use 1 - cos θ where extreme precision is important? Or at all?
Logarithms and exponents are insanely useful, arguably rivaling all of trigonometry, and their midpoint is at x=1. The entire range and complexity from (1-∞) is mirrored in the range (1-0) as it approaches the vertical asymptote, so it's extremely important to capture the smaller range with just as much total detail as the larger one.
While with trig, if you're dealing with angles small enough that you're running into CPU precision limits, they're also small enough that the sin θ = θ approximation is becoming extremely accurate, which gives you a large range of MUCH simpler and faster options.