Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
35
Task/Arithmetic-Complex/Scala/arithmetic-complex-1.scala
Normal file
35
Task/Arithmetic-Complex/Scala/arithmetic-complex-1.scala
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package org.rosettacode
|
||||
|
||||
package object ArithmeticComplex {
|
||||
val i = Complex(0, 1)
|
||||
|
||||
implicit def fromDouble(d: Double) = Complex(d)
|
||||
implicit def fromInt(i: Int) = Complex(i.toDouble)
|
||||
}
|
||||
|
||||
package ArithmeticComplex {
|
||||
case class Complex(real: Double = 0.0, imag: Double = 0.0) {
|
||||
def this(s: String) =
|
||||
this("[\\d.]+(?!i)".r findFirstIn s getOrElse "0" toDouble,
|
||||
"[\\d.]+(?=i)".r findFirstIn s getOrElse "0" toDouble)
|
||||
|
||||
def +(b: Complex) = Complex(real + b.real, imag + b.imag)
|
||||
def -(b: Complex) = Complex(real - b.real, imag - b.imag)
|
||||
def *(b: Complex) = Complex(real * b.real - imag * b.imag, real * b.imag + imag * b.real)
|
||||
def inverse = {
|
||||
val denom = real * real + imag * imag
|
||||
Complex(real / denom, -imag / denom)
|
||||
}
|
||||
def /(b: Complex) = this * b.inverse
|
||||
def unary_- = Complex(-real, -imag)
|
||||
lazy val abs = math.hypot(real, imag)
|
||||
override def toString = real + " + " + imag + "i"
|
||||
|
||||
def i = { require(imag == 0.0); Complex(imag = real) }
|
||||
}
|
||||
|
||||
object Complex {
|
||||
def apply(s: String) = new Complex(s)
|
||||
def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
|
||||
}
|
||||
}
|
||||
26
Task/Arithmetic-Complex/Scala/arithmetic-complex-2.scala
Normal file
26
Task/Arithmetic-Complex/Scala/arithmetic-complex-2.scala
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
scala> import org.rosettacode.ArithmeticComplex._
|
||||
import org.rosettacode.ArithmeticComplex._
|
||||
|
||||
scala> 1 + i
|
||||
res0: org.rosettacode.ArithmeticComplex.Complex = 1.0 + 1.0i
|
||||
|
||||
scala> 1 + 2 * i
|
||||
res1: org.rosettacode.ArithmeticComplex.Complex = 1.0 + 2.0i
|
||||
|
||||
scala> 2 + 1.i
|
||||
res2: org.rosettacode.ArithmeticComplex.Complex = 2.0 + 1.0i
|
||||
|
||||
scala> res0 + res1
|
||||
res3: org.rosettacode.ArithmeticComplex.Complex = 2.0 + 3.0i
|
||||
|
||||
scala> res1 * res2
|
||||
res4: org.rosettacode.ArithmeticComplex.Complex = 0.0 + 5.0i
|
||||
|
||||
scala> res2 / res0
|
||||
res5: org.rosettacode.ArithmeticComplex.Complex = 1.5 + -0.5i
|
||||
|
||||
scala> res1.inverse
|
||||
res6: org.rosettacode.ArithmeticComplex.Complex = 0.2 + -0.4i
|
||||
|
||||
scala> -res6
|
||||
res7: org.rosettacode.ArithmeticComplex.Complex = -0.2 + 0.4i
|
||||
Loading…
Add table
Add a link
Reference in a new issue