Created
November 17, 2025 13:51
-
-
Save antisaling/84a7ec0e9f6d6b03b212c37f922b62a1 to your computer and use it in GitHub Desktop.
fastatan2 odin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package whatever | |
| import "core:math" | |
| import "core:math/simd" | |
| // based on https://gist.github.com/volkansalma/2972237?permalink_comment_id=3872525#gistcomment-3872525 | |
| svec::#simd[4]f32 | |
| HALF_PI :: math.PI / 2. | |
| QUARTER_PI :: math.PI / 4. | |
| ATAN_C1 :: 0.1963 | |
| ATAN_C2 :: 0.9817 | |
| // about 50% faster than math.atan2 | |
| fastatan2 :: proc(y, x: f32) -> f32 { | |
| abs_y := abs(y) + 1e-10 // kludge to prevent 0/0 condition | |
| r := (x - math.copy_sign(abs_y, x)) / (abs_y + abs(x)) | |
| angle := (ATAN_C1 * r * r - ATAN_C2) * r + (HALF_PI - math.copy_sign(QUARTER_PI, x)) | |
| return math.copy_sign(angle, y) | |
| } | |
| SHALF_PI :: svec{HALF_PI, HALF_PI, HALF_PI, HALF_PI} | |
| SQUARTER_PI :: svec{QUARTER_PI, QUARTER_PI, QUARTER_PI, QUARTER_PI} | |
| SATAN_C1 :: svec{ATAN_C1, ATAN_C1, ATAN_C1, ATAN_C1} | |
| SATAN_C2 :: svec{ATAN_C2, ATAN_C2, ATAN_C2, ATAN_C2} | |
| // about 30% faster | |
| sfastatan2 :: proc(y, x: svec) -> svec { | |
| ay := simd.add(simd.abs(y), svec(1e-10)) | |
| r := simd.div(simd.sub(x, simd.copysign(ay, x)), simd.add(ay, simd.abs(x))) | |
| angle := simd.fma(simd.sub(simd.mul(SATAN_C1, simd.mul(r, r)), SATAN_C2), r, simd.sub(SHALF_PI, simd.sign(SQUARTER_PI, x))) | |
| return simd.copysign(angle, y) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment