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

Use unlimited MathContext for BigDecimal arithmetic #3303

Merged
merged 3 commits into from
Feb 24, 2020
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,6 @@ class Tests extends TestsConfig with AnyFunSuiteLike with FunSuiteDiscipline wit
checkAll("Hash[Queue[Int]", HashTests[Queue[Int]].hash)

{
// default Arbitrary[BigDecimal] is a bit too intense :/
implicit val arbBigDecimal: Arbitrary[BigDecimal] =
Arbitrary(arbitrary[Double].map(n => BigDecimal(n.toString)))
checkAll("Order[BigDecimal]", OrderTests[BigDecimal].order)
checkAll("CommutativeGroup[BigDecimal]", CommutativeGroupTests[BigDecimal].commutativeGroup)
checkAll("CommutativeGroup[BigDecimal]", SerializableTests.serializable(CommutativeGroup[BigDecimal]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,20 @@ trait BigDecimalInstances {
new BigDecimalGroup
}

/**
* Note that combining, removing, and inverting `BigDecimal` values will use unlimited precision
* operations.
*
* This matches the behavior of Scala 2.12 and earlier versions, but not Scala 2.13, which means
* that `+` and `|+|` (or `sum` and `combineAll`) may not agree if you are working with values with
* limited-precision `MathContext`s.
*/
class BigDecimalGroup extends CommutativeGroup[BigDecimal] {
val empty: BigDecimal = BigDecimal(0)
def combine(x: BigDecimal, y: BigDecimal): BigDecimal = x + y
def inverse(x: BigDecimal): BigDecimal = -x
override def remove(x: BigDecimal, y: BigDecimal): BigDecimal = x - y
def combine(x: BigDecimal, y: BigDecimal): BigDecimal = new BigDecimal(x.bigDecimal.add(y.bigDecimal), x.mc)
def inverse(x: BigDecimal): BigDecimal = new BigDecimal(x.bigDecimal.negate(), x.mc)
override def remove(x: BigDecimal, y: BigDecimal): BigDecimal =
new BigDecimal(x.bigDecimal.subtract(y.bigDecimal), x.mc)
}

class BigDecimalOrder extends Order[BigDecimal] with Hash[BigDecimal] {
Expand Down