|
Re: Scala generics for automatic differentiation: msg#00281lang.scala
Michel Salim wrote: > > Calculating higher-order derivatives is when C++ makes it look simple > ... > template<class X> > class Dual { > public: > X a; > X b; > ... > Hi Michel, Your Scala code needs to similarly make Dual a template. One way to do this appears below. Hopefully it can be made more concise, perhaps fromDouble can be replaced by an implicit conversion. Regards, Eric. trait Arithmetic[t <: Arithmetic[t]] { def +(y: t): t def *(y: t): t def fromDouble(x: Double): t } case class MyDouble(a: Double) extends Arithmetic[MyDouble] { def +(y: MyDouble) = MyDouble(this.a + y.a) def *(y: MyDouble) = MyDouble(this.a * y.a) def fromDouble(x: Double) = MyDouble(x) } case class Dual[t <: Arithmetic[t]](a: t, b: t) extends Arithmetic[Dual[t]] { def +(y: Dual[t]) = Dual[t](this.a + y.a, this.b + y.b) def *(y: Dual[t]) = Dual[t](this.a * y.a, this.b * y.a + this.a * y.b) def fromDouble(x: Double) = Dual[t](a.fromDouble(x), b.fromDouble(0)) // not currently used:- // def d() = Dual[t](a.fromDouble(0), b.fromDouble(1)) } object DualTest { def diff[t <: Arithmetic[t]](fn: Dual[t] => Dual[t])(n: t) = fn(Dual[t](n, n.fromDouble(1))).b def f[t <: Arithmetic[t]](x: Dual[t]) = (x + x.fromDouble(2)) * (x + x.fromDouble(1)) def g[t <: Arithmetic[t]](x: Dual[t]) = diff(f)(x) def h[t <: Arithmetic[t]](x: t) = diff(g)(x) def main(args: Array[String]): Unit = { Console.println(diff[MyDouble](f)(MyDouble(20))) Console.println(h(MyDouble(3))) } } -- View this message in context: http://www.nabble.com/Scala-generics-for-automatic-differentiation-tf3052000.html#a8521465 Sent from the Scala mailing list archive at Nabble.com. |
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Re: A useful list operator: 00281, Burak Emir |
|---|---|
| Next by Date: | Re: IRC channel update: 00281, Lex Spoon |
| Previous by Thread: | Scala generics for automatic differentiationi: 00281, Michel Salim |
| Next by Thread: | Re: Scala generics for automatic differentiation: 00281, Michel Salim |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |