Skip to content

Commit

Permalink
chore(Data/Rat): move Float functions to separate file (#1035)
Browse files Browse the repository at this point in the history
Co-authored-by: Kim Morrison <[email protected]>
  • Loading branch information
jcommelin and kim-em authored Nov 12, 2024
1 parent 12381da commit 44f2360
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 16 deletions.
1 change: 1 addition & 0 deletions Batteries/Data/Rat.lean
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
import Batteries.Data.Rat.Basic
import Batteries.Data.Rat.Float
import Batteries.Data.Rat.Lemmas
17 changes: 1 addition & 16 deletions Batteries/Data/Rat/Basic.lean
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Batteries.Data.Nat.Gcd
import Batteries.Lean.Float

/-! # Basics for the Rational Numbers -/

Expand Down Expand Up @@ -278,18 +277,4 @@ protected def ceil (a : Rat) : Int :=
else
a.num / a.den + 1

/-- Convert this rational number to a `Float` value. -/
protected def toFloat (a : Rat) : Float := a.num.divFloat a.den

/-- Convert this floating point number to a rational value. -/
protected def _root_.Float.toRat? (a : Float) : Option Rat :=
a.toRatParts.map fun (v, exp) =>
mkRat (v.sign * v.natAbs <<< exp.toNat) (1 <<< (-exp).toNat)

/--
Convert this floating point number to a rational value,
mapping non-finite values (`inf`, `-inf`, `nan`) to 0.
-/
protected def _root_.Float.toRat0 (a : Float) : Rat := a.toRat?.getD 0

instance : Coe Rat Float := ⟨Rat.toFloat⟩
end Rat
29 changes: 29 additions & 0 deletions Batteries/Data/Rat/Float.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Batteries.Data.Rat.Basic
import Batteries.Lean.Float

/-! # Rational Numbers and Float -/

namespace Rat

/-- Convert this rational number to a `Float` value. -/
protected def toFloat (a : Rat) : Float := a.num.divFloat a.den

/-- Convert this floating point number to a rational value. -/
protected def _root_.Float.toRat? (a : Float) : Option Rat :=
a.toRatParts.map fun (v, exp) =>
mkRat (v.sign * v.natAbs <<< exp.toNat) (1 <<< (-exp).toNat)

/--
Convert this floating point number to a rational value,
mapping non-finite values (`inf`, `-inf`, `nan`) to 0.
-/
protected def _root_.Float.toRat0 (a : Float) : Rat := a.toRat?.getD 0

instance : Coe Rat Float := ⟨Rat.toFloat⟩

end Rat

0 comments on commit 44f2360

Please sign in to comment.