这是关于 Scala Numeric[T] 的问题的另一个问题。
我今天稍微更改了代码,以支持牛顿估计下一个最佳种子。一切都好,除了现在不能A.fromDouble(v)
真正杀人的事实(?)。
这是一个有点长的样本,但最好把所有的都放在这里。
import scala.annotation.tailrec
import math.{signum => sign}
import math.Fractional.Implicits._
import Ordering.Implicits._
/*
* 'f' is a "strictly increasing function" (derivative > 0).
* The sweep gives the value at which it gives 'goal' (within '+-bEps' margins).
*/
object NewtonianSweep {
def apply[A: Fractional, B: Fractional](
f: A => B,
fDerivate: A => Double,
goal: B,
bEps: B,
initialSeed: A,
aMin: A,
aMax: A
): A = {
assert( initialSeed >= aMin && initialSeed <= aMax )
// 'goal' is supposed to exist within the range (this also checks that
// the function is increasing - though doesn't (cannot) check "strict increasing",
// we'll just trust the caller.
//
assert( f(aMin) <= goal )
assert( f(aMax) >= goal )
@tailrec
def sweep( _seed: A ): A = {
val seed= _seed.max(aMin).min(aMax) // keep 'seed' within range
val bDiff= goal-f(seed) // >0 for heading higher, <0 for heading lower
if (bDiff.abs < bEps) {
seed // done (within margins)
} else {
val d= fDerivate(seed) // slope at the particular position (dy/dx)
assert( d>0.0 )
// TBD: How to get the calculated 'Double' to be added to 'seed: A'?
//
val aType= implicitly[Fractional[A]]
sweep( aType.plus( seed, aType.fromDouble( d*(bDiff.toDouble) ) ))
}
}
sweep( initialSeed )
}
}
我有两种Fractional
类型A
和的原因B
是它们在概念上是不同的。A
通常是时间。B
可以是任何东西。如果我要为它们使用相同的类型,我也可以说它们是Double
's。
在我这样做之前,我想检查是否有人有这个问题的缺失部分。