Skip to content

Commit

Permalink
Mod for BDouble (#51)
Browse files Browse the repository at this point in the history
* mod for BDouble

* Increase version number

* add precondition to mod
  • Loading branch information
twodayslate authored Oct 22, 2020
1 parent 9454066 commit 8e8423b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion BigNumber.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Pod::Spec.new do |s|
#

s.name = "BigNumber"
s.version = "2.1.1"
s.version = "2.2.0"
s.summary = "A lightweight, high performance bignum library for Swift!"

# This description is used to generate tags and improve search results.
Expand Down
15 changes: 15 additions & 0 deletions Sources/Swift-Big-Number-Core.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2414,6 +2414,7 @@ public struct BDouble:
self.init(z, over: 1)
}

/// Warning: Due to the inprecision of Double beware that this might effect the precision of your BDouble
public init(_ d: Double)
{
let nStr = String(d)
Expand Down Expand Up @@ -2926,6 +2927,10 @@ public struct BDouble:
public static func /(lhs: BDouble, rhs: Double) -> BDouble { return lhs / BDouble(rhs) }
public static func /(lhs: BDouble, rhs: BInt) -> BDouble { return lhs / BDouble(rhs) }
public static func /(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) / rhs }

public static func %(lhs: BDouble, rhs:BDouble) -> BDouble { return mod(lhs, rhs) }
public static func %(lhs: BDouble, rhs:Double) -> BDouble { return mod(lhs, BDouble(rhs)) }
public static func %(lhs: Double, rhs:BDouble) -> BDouble { return mod(BDouble(lhs), rhs) }

//
//
Expand Down Expand Up @@ -3138,3 +3143,13 @@ public func max(_ lhs: BDouble, _ rhs: BDouble) -> BDouble {
}
return rhs
}

/**
* Returns the modulo (remainder)
*/
public func mod(_ lhs: BDouble, _ rhs: BDouble) -> BDouble {
precondition(!rhs.isZero(), "Right hand side cannot be zero")
let inner_ceil: BDouble = -lhs/rhs
let _ceil: BDouble = BDouble(ceil(inner_ceil))
return lhs + (rhs*_ceil)
}
15 changes: 15 additions & 0 deletions Tests/BDoubleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,21 @@ class BDoubleTests : XCTestCase {
}
}

func test_mod() {
let answers = [
("5.0", "2.6", "2.4"),
("10000.5234", "6.4774", "5.8952"),
("-108700.5234", "6.4774", "3.2034"),
("-1.5234", "6.4774", "4.954"),
("1.5234", "6.4774", "1.5234"),
("0", "1000", "0"),
]

for ans in answers {
XCTAssertEqual(mod(BDouble(ans.0)!, BDouble(ans.1)!), BDouble(ans.2)!)
XCTAssertEqual(BDouble(ans.0)! % BDouble(ans.1)!, BDouble(ans.2)!)
}
}

func testDecimalExpansionWithoutRounding()
{
Expand Down

0 comments on commit 8e8423b

Please sign in to comment.