Skip to content

Instantly share code, notes, and snippets.

@alabamenhu
Created March 5, 2023 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alabamenhu/e0770fc0b978d579eeb2315adb429a03 to your computer and use it in GitHub Desktop.
Save alabamenhu/e0770fc0b978d579eeb2315adb429a03 to your computer and use it in GitHub Desktop.
Magnitude function
#| 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