Skip to content

Commit

Permalink
added ceil, floor, and rounded to BDouble
Browse files Browse the repository at this point in the history
  • Loading branch information
twodayslate committed Dec 21, 2017
1 parent 05f76d8 commit c1a15c9
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions Sources/SMP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2421,6 +2421,30 @@ public struct BDouble:
}
}

public func rounded() -> BInt
{
if self.isZero() {
return BInt(0)
}
let digits = 3
let multiplier = [10].exponentiating(digits)

let rawRes = self.numerator.multiplyingBy(multiplier).divMod(self.denominator).quotient

let res = BInt(limbs: rawRes).description

let offset = res.count - digits
let rhs = Double("0." + res.suffix(offset+1))!
let lhs = res.prefix(offset)
var retVal = BInt(String(lhs))!
if rhs > 0.5
{
retVal = retVal + 1
}

return retVal
}

// public func sqrt(precision digits: Int) -> BDouble
// {
// // let self = v
Expand Down Expand Up @@ -2561,3 +2585,61 @@ public func abs(_ lhs: BDouble) -> BDouble
denominator: lhs.denominator
)
}

// TODO: pow function that supports Double/BDouble in the expontent
public func pow(_ base : BDouble, _ expontent : Int) -> BDouble
{
if expontent == 0
{
return BDouble(1)
}
if expontent == 1
{
return base
}
if expontent < 0
{
return BDouble(1) / pow(base, -expontent)
}

return base * pow(base, expontent-1)
}

public func floor(_ base: BDouble) -> BInt
{
let digits = 3
let multiplier = [10].exponentiating(digits)

let rawRes = base.numerator.multiplyingBy(multiplier).divMod(base.denominator).quotient

let res = BInt(limbs: rawRes).description

let offset = res.count - digits
let lhs = res.prefix(offset)

return BInt(String(lhs))!
}

public func ceil(_ base: BDouble) -> BInt
{
if base.isZero() {
return BInt(0)
}
let digits = 3
let multiplier = [10].exponentiating(digits)

let rawRes = base.numerator.multiplyingBy(multiplier).divMod(base.denominator).quotient

let res = BInt(limbs: rawRes).description

let offset = res.count - digits
let rhs = Double("0." + res.suffix(offset+1))!
let lhs = res.prefix(offset)
var retVal = BInt(String(lhs))!
if rhs > 0.0
{
retVal = retVal + 1
}

return retVal
}

0 comments on commit c1a15c9

Please sign in to comment.