Skip to content
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
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 198 additions & 0 deletions laws/src/main/scala/cats/laws/discipline/MiniFloat.scala
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)
}
Comment on lines +178 to +186
Copy link
Contributor Author

@tmccarthy tmccarthy Nov 1, 2021

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 that NaN == NaN. I'm aware that this is slightly unintuitive but otherwise the Eq 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.


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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assuming we define Eq[MiniFloat] as above, I believe this is the main lawful Monoid you can define for MiniFloat. I'd be happy to provide instances for addition and multiplication (with appropriate tests and disclaimers) if requested, but I'm not sure they'd be super useful.


}
7 changes: 7 additions & 0 deletions laws/src/main/scala/cats/laws/discipline/arbitrary.scala
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,13 @@ object arbitrary extends ArbitraryInstances0 with ScalaVersionSpecific.Arbitrary

implicit val catsLawsArbitraryForMiniInt: Arbitrary[MiniInt] =
Arbitrary(Gen.oneOf(MiniInt.allValues))

implicit val catsLawsCogenForMiniFloat: Cogen[MiniFloat] =
Cogen[Float].contramap(_.toFloat)

implicit val catsLawsArbitraryForMiniFloat: Arbitrary[MiniFloat] =
Arbitrary(Gen.oneOf(MiniFloat.allValues))

}

sealed private[discipline] trait ArbitraryInstances0 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ package cats.tests
import cats.kernel.{Eq, Order}
import cats.laws.discipline.{ExhaustiveCheck, MiniInt}
import cats.laws.discipline.MiniInt._
import cats.laws.discipline.MiniFloat
import cats.laws.discipline.eq._
import cats.laws.discipline.DeprecatedEqInstances
import org.scalacheck.Arbitrary

trait ScalaVersionSpecificFoldableSuite
trait ScalaVersionSpecificParallelSuite
Expand All @@ -51,48 +50,48 @@ trait ScalaVersionSpecificAlgebraInvariantSuite {
}

// This version-specific instance is required since 2.12 and below do not have parseString on the Numeric class
implicit protected def eqNumeric[A: Eq: ExhaustiveCheck]: Eq[Numeric[A]] = Eq.by { numeric =>
// This allows us to catch the case where the fromInt overflows. We use the None to compare two Numeric instances,
// verifying that when fromInt throws for one, it throws for the other.
val fromMiniInt: MiniInt => Option[A] =
miniInt =>
try Some(numeric.fromInt(miniInt.toInt))
catch {
case _: IllegalArgumentException => None // MiniInt overflow
}
protected val fractionalForMiniFloat: Fractional[MiniFloat] = new Fractional[MiniFloat] {
def compare(x: MiniFloat, y: MiniFloat): Int = Order[MiniFloat].compare(x, y)
def plus(x: MiniFloat, y: MiniFloat): MiniFloat = x + y
def minus(x: MiniFloat, y: MiniFloat): MiniFloat = x + (-y)
def times(x: MiniFloat, y: MiniFloat): MiniFloat = x * y
def div(x: MiniFloat, y: MiniFloat): MiniFloat = x / y
def negate(x: MiniFloat): MiniFloat = -x
def fromInt(x: Int): MiniFloat = MiniFloat.from(x)
def toInt(x: MiniFloat): Int = x.toInt
def toLong(x: MiniFloat): Long = x.toInt.toLong
def toFloat(x: MiniFloat): Float = x.toInt.toFloat
def toDouble(x: MiniFloat): Double = x.toInt.toDouble
}

/**
* Emulates the behaviour of `Numeric#fromInt`, but using MiniInt as the input. This allows us to exercise the
* implementation of `fromInt` for an instance of `Numeric` while still taking advantage of the `ExhaustiveCheck`
* instance for `MiniInt`.
*
* Note that this will return `None` when `fromInt` overflows. We can use this to compare two `Numeric` instances,
* verifying that when `fromInt` throws for one, it throws for the other.
*/
private def numericFromMiniInt[A](miniInt: MiniInt, numeric: Numeric[A]): Option[A] =
try Some(numeric.fromInt(miniInt.toInt))
catch {
case _: IllegalArgumentException => None // MiniInt overflow
}

// This version-specific instance is required since 2.12 and below do not have parseString on the Numeric class
implicit protected def eqNumeric[A: Eq: ExhaustiveCheck]: Eq[Numeric[A]] = Eq.by { numeric =>
(
numeric.compare _,
numeric.plus _,
numeric.minus _,
numeric.times _,
numeric.negate _,
fromMiniInt,
numericFromMiniInt[A](_, numeric),
numeric.toInt _,
numeric.toLong _,
numeric.toFloat _,
numeric.toDouble _
)
}

// This version-specific instance is required since 2.12 and below do not have parseString on the Numeric class
@annotation.nowarn("cat=deprecation")
implicit protected def eqFractional[A: Eq: Arbitrary]: Eq[Fractional[A]] = {
import DeprecatedEqInstances.catsLawsEqForFn1

Eq.by { fractional =>
(
fractional.compare _,
fractional.plus _,
fractional.minus _,
fractional.times _,
fractional.negate _,
fractional.fromInt _,
fractional.toInt _,
fractional.toLong _,
fractional.toFloat _,
fractional.toDouble _
)
}
}
}
Loading