-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add small-domain floating-point type MiniFloat to discipline package #4033
Closed
Closed
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
2d9203b
Add MiniFloat
tmccarthy 9514cff
Some more notes on the Eq instance for MiniFloat
tmccarthy 5042937
Add laws tests for order and hash for MiniFloat
tmccarthy 822e354
Fix typo in MiniInt tests
tmccarthy 057f408
Remove references to group tests, which are too unlawful to be useful
tmccarthy 236957f
Fixes for Scala 2.12 and Scala 3
tmccarthy 187619d
MiniFloat maximum instance and tests
tmccarthy bbd7d7c
Merge branch 'main' into minifloat
tmccarthy 09bac12
Provide an implimentation to get the exponent of a Float. Can't use t…
tmccarthy d157328
More on the docs for MiniFloat
tmccarthy 16bee38
Fix zero reference
tmccarthy 27f7014
Merge branch 'main' into minifloat
tmccarthy a5243d7
Merge branch 'main' into minifloat
tmccarthy 537f7e0
Use MiniFloat to test Invariant[Fractional], instead of using Float.
tmccarthy 3d77c96
Add headers to MiniFloat and test
tmccarthy f026629
Formatting
tmccarthy 2e92db5
Define eqFractional in AlgebraInvariantSuite
tmccarthy 32f06d0
Add dedicated test for NaN hash consistency with universal hash. Has …
tmccarthy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
198 changes: 198 additions & 0 deletions
198
laws/src/main/scala/cats/laws/discipline/MiniFloat.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,198 @@ | ||
/* | ||
* Copyright (c) 2015 Typelevel | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy of | ||
* this software and associated documentation files (the "Software"), to deal in | ||
* the Software without restriction, including without limitation the rights to | ||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | ||
* the Software, and to permit persons to whom the Software is furnished to do so, | ||
* subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all | ||
* copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | ||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | ||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | ||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
*/ | ||
|
||
package cats | ||
package laws | ||
package discipline | ||
|
||
import cats.implicits.{catsSyntaxPartialOrder, toTraverseFilterOps} | ||
import cats.kernel.{BoundedSemilattice, CommutativeMonoid} | ||
|
||
/** | ||
* Similar to `Float`, but with a much smaller domain. The exact range of [[MiniFloat]] may be tuned from time to time, | ||
* so consumers of this type should avoid depending on its exact range. | ||
* | ||
* `MiniFloat` has overflow and floating-point error characteristics similar to `Float`, but these are exaggerated due | ||
* to its small domain. It is only approximately commutative and associative under addition and multiplication, due to | ||
* floating-point errors, overflows, and the behaviour of `NaN`. | ||
* | ||
* Note that unlike `Float`, `MiniFloat` does not support the representation of negative zero (`-0f`). | ||
*/ | ||
sealed abstract class MiniFloat private (val toFloat: Float) { | ||
def toDouble: Double = toFloat.toDouble | ||
def toInt: Int = toFloat.toInt | ||
def toLong: Long = toFloat.toLong | ||
|
||
def +(that: MiniFloat): MiniFloat = MiniFloat.from(this.toFloat + that.toFloat) | ||
def -(that: MiniFloat): MiniFloat = MiniFloat.from(this.toFloat - that.toFloat) | ||
def *(that: MiniFloat): MiniFloat = MiniFloat.from(this.toFloat * that.toFloat) | ||
def /(that: MiniFloat): MiniFloat = MiniFloat.from(this.toFloat / that.toFloat) | ||
def unary_- : MiniFloat = MiniFloat.from(-this.toFloat) | ||
|
||
def isNaN: Boolean = toFloat.isNaN | ||
def isFinite: Boolean = java.lang.Float.isFinite(toFloat) | ||
|
||
override def toString = s"MiniFloat($toFloat)" | ||
|
||
override def equals(other: Any): Boolean = other match { | ||
case that: MiniFloat => this.toFloat == that.toFloat | ||
case _ => false | ||
} | ||
|
||
override def hashCode: Int = java.lang.Float.hashCode(toFloat) | ||
|
||
} | ||
|
||
object MiniFloat { | ||
|
||
object PositiveInfinity extends MiniFloat(Float.PositiveInfinity) | ||
object NegativeInfinity extends MiniFloat(Float.NegativeInfinity) | ||
object NaN extends MiniFloat(Float.NaN) | ||
|
||
final private class Finite private (significand: Int, exponent: Int) | ||
extends MiniFloat(significand * math.pow(Finite.base.toDouble, exponent.toDouble).toFloat) | ||
|
||
private[MiniFloat] object Finite { | ||
|
||
private[MiniFloat] val base = 2 | ||
|
||
private val minSignificand = -2 | ||
private val maxSignificand = 2 | ||
|
||
private val minExponent = -1 | ||
private val maxExponent = 2 | ||
|
||
val allValues: List[Finite] = { | ||
for { | ||
significand <- Range.inclusive(minSignificand, maxSignificand) | ||
exponent <- Range.inclusive(minExponent, maxExponent) | ||
} yield new Finite(significand, exponent) | ||
}.toList.ordDistinct(Order.by[Finite, Float](_.toFloat)).sortBy(_.toFloat) | ||
|
||
private[MiniFloat] val allValuesAsFloats: List[Float] = allValues.map(_.toFloat) | ||
|
||
val zero = new Finite(0, 0) | ||
val max = new Finite(maxSignificand, maxExponent) | ||
val min = new Finite(minSignificand, maxExponent) | ||
val minPositive = new Finite(significand = 1, exponent = minExponent) | ||
|
||
/** | ||
* Returns `None` if the given float cannot fit in an instance of `Finite`. | ||
*/ | ||
def from(float: Float): Option[Finite] = { | ||
val exponent: Int = getExponent(float) | ||
val significand: Int = math.round(float / math.pow(Finite.base.toDouble, exponent.toDouble).toFloat) | ||
|
||
if (significand == 0 || exponent < minExponent) { | ||
Some(zero) | ||
} else if (withinBounds(significand, exponent)) { | ||
Some(new Finite(significand, exponent)) | ||
} else if (exponent > maxExponent) { | ||
try { | ||
val ordersOfMagnitudeToShift = Math.subtractExact(exponent, maxExponent) | ||
|
||
val proposedSignificand: Int = Math.multiplyExact( | ||
significand, | ||
math.pow(base.toDouble, ordersOfMagnitudeToShift.toDouble).toInt | ||
) | ||
val proposedExponent: Int = Math.subtractExact(exponent, ordersOfMagnitudeToShift) | ||
|
||
if (withinBounds(proposedSignificand, proposedExponent)) { | ||
Some(new Finite(proposedSignificand, proposedExponent)) | ||
} else { | ||
None | ||
} | ||
} catch { | ||
case _: ArithmeticException => None | ||
} | ||
} else { | ||
None | ||
} | ||
} | ||
|
||
private def withinBounds(significand: Int, exponent: Int): Boolean = | ||
(minExponent <= exponent && exponent <= maxExponent) && | ||
(minSignificand <= significand && significand <= maxSignificand) | ||
|
||
private val floatExponentStartBit: Int = 23 | ||
private val floatExponentLength: Int = 8 | ||
private val floatExponentBias: Int = 127 | ||
private val floatExponentMask: Int = ((1 << floatExponentLength) - 1) << floatExponentStartBit | ||
|
||
// This does the same thing as java.lang.Math.getExponent, but that method is not available in scalaJS so we have to | ||
// do the same thing here. | ||
private def getExponent(float: Float): Int = | ||
((floatExponentMask & java.lang.Float.floatToIntBits(float)) >> floatExponentStartBit) - floatExponentBias | ||
|
||
} | ||
|
||
val Zero: MiniFloat = Finite.zero | ||
val NegativeOne: MiniFloat = MiniFloat.from(-1f) | ||
val One: MiniFloat = MiniFloat.from(1f) | ||
|
||
val MaxValue: MiniFloat = Finite.max | ||
val MinValue: MiniFloat = Finite.min | ||
val MinPositiveValue: MiniFloat = Finite.minPositive | ||
|
||
def allValues: List[MiniFloat] = | ||
List(NegativeInfinity) ++ | ||
Finite.allValues :+ | ||
PositiveInfinity :+ | ||
NaN | ||
|
||
def from(float: Float): MiniFloat = | ||
float match { | ||
case Float.PositiveInfinity => PositiveInfinity | ||
case Float.NegativeInfinity => NegativeInfinity | ||
case f if f.isNaN => NaN | ||
case _ => | ||
Finite | ||
.from(float) | ||
.getOrElse { | ||
if (float > 0) PositiveInfinity else NegativeInfinity | ||
} | ||
} | ||
|
||
def from(double: Double): MiniFloat = from(double.toFloat) | ||
def from(int: Int): MiniFloat = from(int.toFloat) | ||
def from(long: Long): MiniFloat = from(long.toFloat) | ||
|
||
/** | ||
* Note that since `MiniFloat` is used primarily for tests, this `Eq` instance defines `NaN` as equal to itself. This | ||
* differs from the `Order` defined for `Float`. | ||
*/ | ||
implicit val catsLawsEqInstancesForMiniFloat: Order[MiniFloat] with Hash[MiniFloat] = | ||
new Order[MiniFloat] with Hash[MiniFloat] { | ||
override def compare(x: MiniFloat, y: MiniFloat): Int = Order[Float].compare(x.toFloat, y.toFloat) | ||
override def hash(x: MiniFloat): Int = Hash[Float].hash(x.toFloat) | ||
} | ||
|
||
implicit val catsLawsExhaustiveCheckForMiniInt: ExhaustiveCheck[MiniFloat] = new ExhaustiveCheck[MiniFloat] { | ||
override def allValues: List[MiniFloat] = MiniFloat.allValues | ||
} | ||
|
||
val miniFloatMax: CommutativeMonoid[MiniFloat] with BoundedSemilattice[MiniFloat] = | ||
new CommutativeMonoid[MiniFloat] with BoundedSemilattice[MiniFloat] { | ||
override def empty: MiniFloat = MiniFloat.NegativeInfinity | ||
override def combine(x: MiniFloat, y: MiniFloat): MiniFloat = if (x > y) x else y | ||
} | ||
Comment on lines
+192
to
+196
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Assuming we define |
||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because we're using this class in tests it's really only useful if we define
Eq
such thatNaN == NaN
. I'm aware that this is slightly unintuitive but otherwise theEq
instance becomes useless.An alternative approach would be to provide this
Eq
in such a way that it needs to be manually imported when used. I'd be happy to make that change as needed.