Posit numbers/decoding: Difference between revisions
→{{header|raku}}: rewrite
(Added Wren) |
(→{{header|raku}}: rewrite) |
||
Line 14:
=={{header|raku}}==
<syntaxhighlight lang=raku>unit role Posit[UInt $
has
method sign { self.UInt > 2**($N - 1) ?? -1 !! +1 }
sub useed { 2**(2**$es) }▼
my UInt $mask = 2**($N - 1);
return Inf if self.UInt == $mask;
my UInt $n = self.UInt;
my $r = $sign;
$n = ((2**$n - 1) +^ $n) + 1 if self.sign < 0;
my int $count = 0;
repeat { $count++; $mask +>= 1;
} while ?($n +& $mask) == $first-bit && $mask;
my $m = $count;
$mask +>= 1;
$count = 0;
my UInt $exponent = 0;
while $mask && $count++ < $es {
$exponent +<= 1;
$exponent +|= 1 if $n +& $mask;
$mask +>= 1;
$r *= 2**$exponent;
while $mask {
(state $power-of-two = 1) +<= 1;
$fraction += 1/$power-of-two if $n +& $mask;
$mask +>= 1;
$r *= $fraction;
return $r;
▲ (
▲ (
▲ + 1
▲method Real {
▲ return 0 unless @!bits.any;
▲ return Inf if self ~~ /^10*$/;
▲ my $sign = @!bits.head ?? -1 !! +1;
▲ token fraction { <.bit>+ }
▲ my $first-bit = $/.Str.substr(0,1);
▲ make useed**($first-bit eq '1' ?? $m - 1 !! -$m);
}
Line 71 ⟶ 60:
# example from L<http://www.johngustafson.net/pdfs/BeatingFloatingPoint.pdf>
is Posit[16, 3]
.new(
}</syntaxhighlight>
|