Posit numbers/decoding: Difference between revisions
Content added Content deleted
(julia example) |
m (→{{header|Julia}}: simplify zero handling) |
||
Line 23: | Line 23: | ||
""" From posithub.org/docs/Posits4.pdf """ |
""" From posithub.org/docs/Posits4.pdf """ |
||
function Base.Rational(p::PositType3) |
function Base.Rational(p::PositType3) |
||
s = signbit(p.bits) # s for S signbit, is 1 if negative |
|||
pabs = p.bits << 1 # shift off signbit (adds a 0 to F at LSB) |
|||
pabs == 0 && return s ? 1 // 0 : 0 // 1 # if p is 0, return 0 if s = 0, error if s = 1 |
|||
expsign = signbit(pabs) # exponent sign from 2nd bit now in MSB location |
|||
k = expsign == 1 ? leading_ones(pabs) : leading_zeros(pabs) # regime R bit count |
|||
scaling = 2^p.es * (expsign == 0 ? -1 : 1) |
|||
pabs <<= (k + 1) # shift off unwanted R bits |
|||
pabs >>= (k + 2) # shift back without the extra LSB bit |
|||
fsize = p.numbits - k - p.es - 2 # check how many F bits are actually explicit |
|||
fsize <= 0 && return 0 // 1 # missing F is 0 |
|||
f = (pabs & (2^fsize - 1)) // 2^fsize # Get F value. Can be missing -> 0 |
|||
e = |
|||
e = pabs >> fsize # Get E value. |
|||
pw = (1 - 2s) * (scaling * k + e + s) |
|||
pabs * 2^(p.es - p.numbits - k - 2) # implicit missing bits correction |
|||
return pw >= 0 ? ((1 - 3s) + f) * 2^pw // 1 : ((1 - 3s) + f) // 2^(-pw) |
|||
return pw >= 0 ? ((1 - 3s) + f) * 2^pw // 1 : ((1 - 3s) + f) // 2^(-pw) |
|||
end |
end |
||
@show Rational(PositType3(16, 3, 0b0000110111011101)) == 477 // 134217728 |
@show Rational(PositType3(16, 3, 0b0000110111011101)) == 477 // 134217728 |
||
</syntaxhighlight>{{out}} <pre> Rational(PositType3(16, 3, 0x0ddd)) == 477 // 134217728 = true</pre> |
</syntaxhighlight>{{out}} <pre> Rational(PositType3(16, 3, 0x0ddd)) == 477 // 134217728 = true</pre> |
||
=={{header|raku}}== |
=={{header|raku}}== |