Skip to content

Instantly share code, notes, and snippets.

@snowflower
Created January 9, 2025 08:54
Show Gist options
  • Save snowflower/5f8fe7f276ccc3d43f7a83f7e77f29df to your computer and use it in GitHub Desktop.
Save snowflower/5f8fe7f276ccc3d43f7a83f7e77f29df to your computer and use it in GitHub Desktop.
Compute exp(x) - 1 without loss of precision for small values of x. example snippet from godot game code
##
## Compute exp(x) - 1 without loss of precision for small values of x.
## https://www.johndcook.com/blog/cpp_expm1/
##
## usage for exponential smoothing in games/animation e.g.:
## for any value of dt (delta time):
##
## position += (target - position) * (1 - exp(- speed * dt))
##
## changed to use -expm1(x) instead of 1-exp(x)
##
## position += (target - position) * (- _expm1(-speed * dt))
##
## related references:
## https://lisyarus.github.io/blog/posts/exponential-smoothing.html
## https://blog.pkh.me/p/41-fixing-the-iterative-damping-interpolation-in-video-games.html
## https://news.ycombinator.com/item?id=40401152
##
func _expm1(x):
if (abs(x) < 1e-5):
return x + 0.5*x*x;
else:
return exp(x) - 1.0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment