-
-
Save alabamenhu/e0770fc0b978d579eeb2315adb429a03 to your computer and use it in GitHub Desktop.
Magnitude function
This file contains 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
#| Calculates the position of the first digit. Only accepts values ≥ 0 | |
sub magnitude($no is raw) { | |
# Special case 0 to avoid infinite loop | |
return 1 if $no == 0; | |
# Need a copy, because binding is slightly faster faster, `is copy` complains about LHA | |
my $n := $no; | |
my $result := 1; | |
# If less than 1, our result will be negative. Get $n to be positive first | |
while $n < 1 { $result := $result - 8; $n := $n * 10000_0000 } | |
# Int math is MUCH faster, ditto for multiplication. | |
$n := $n.Int; my $comp := 1; | |
# Bump up the result and comparison values. These can be different, but | |
# 8/4/1 seems to be a nice happy balance of speed/complexity. | |
while $n > $comp { $result := $result + 8; $comp := $comp * 10000_0000 } | |
while $n > $comp { $result := $result + 4; $comp := $comp * 10000 } | |
while $n > $comp { $result := $result + 1; $comp := $comp * 10 } | |
# The position of the first digit | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment