library colibrilib.fbin — module Floatmodule Float182use int.Int183use int.Power184use int.EuclideanDivision185use real.RealInfix186use real.FromInt187use colibrilib.fp.Widen188use colibrilib.fp.Ereal as E189use Pow2r190use Format191
Finite neg k: the sign (true for negative) and the magnitude
type value = NaN | PlusInf | MinusInf | Finite bool int194195predicate valid (fm: format) (v: value) =196match v with Finite _ k -> 0 <= k < nb_sign fm - 1 | _ -> true end197Valid (13ms) (colibri2)198type t = { fmt: format; value: value }199invariant { valid fmt value }200by { fmt = { eb = 2; sb = 2 }; value = NaN }201Valid (13ms) (colibri2)202let function mk (fm: format) (v: value) : t203requires { valid fm v }204ensures { result.fmt = fm /\ result.value = v }205= { fmt = fm; value = v }206
The mode on the magnitudes of the negative reals
let function mirror (m: mode) : mode =209match m with RTP -> RTN | RTN -> RTP | _ -> m end210
The magnitude of the rounding of r >= 0, without overflow
function round_mag (fm: format) (m: mode) (r: real) : int =213let k = kdn fm r in214if vom fm k = r then k else215let mid = (vom fm k +. vom fm (k + 1)) /. 2.0 in216match m with217| RTN | RTZ -> k218| RTP -> k + 1219| RNE -> if r <. mid then k else if mid <. r then k + 1220else if mod k 2 = 0 then k else k + 1221| RNA -> if r <. mid then k else k + 1222end223
The float of the magnitude k >= 0, rounded in the mode m of the magnitudes: on overflow, the largest finite float toward zero, else the infinity (IEEE 754 §7.4)
function of_mag (fm: format) (m: mode) (neg: bool) (k: int) : t =228if k < nb_sign fm - 1 then mk fm (Finite neg k)229else match m with230| RTN | RTZ -> mk fm (Finite neg (nb_sign fm - 2))231| _ -> mk fm (if neg then MinusInf else PlusInf)232end233
The rounding of a real; a zero result is –0 if zneg
function round_fin (fm: format) (m: mode) (zneg: bool) (r: real) : t =236if 0.0 <=. r then237let k = round_mag fm m r in238if k = 0 then mk fm (Finite zneg 0) else of_mag fm m false k239else240let k = round_mag fm (mirror m) (-. r) in241if k = 0 then mk fm (Finite zneg 0) else of_mag fm (mirror m) true k242
The real of a finite float (0 for the others)
function to_real (x: t) : real =245match x.value with246| Finite neg k -> if neg then -. vom x.fmt k else vom x.fmt k247| _ -> 0.0248end249250function round_f (fm: format) (m: mode) (zneg: bool) (e: E.ereal) : t =251match e with252| E.Fin r -> round_fin fm m zneg r253| E.PInf -> mk fm PlusInf254| E.MInf -> mk fm MinusInf255end256end257