This repository has been archived by the owner on Aug 1, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #27 from loustler/chapter4
Add solution for exercise 4.2
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 24 additions & 0 deletions
24
src/main/scala/com/chobostudy/loustler/error/SolutionP68.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package com.chobostudy.loustler.error | ||
|
||
import com.chobostudy.loustler.error.Option | ||
|
||
/** | ||
* @author loustler | ||
* @since 11/03/2017 21:19 | ||
*/ | ||
trait SolutionP68 { | ||
def mean(xs: Seq[Double]): Option[Double] = { | ||
Option(xs.sum / xs.size) | ||
} | ||
|
||
// exercise 4.2 | ||
def variance(xs: Seq[Double]): Option[Double] = { | ||
Option(xs).flatMap(x => { | ||
val meanV = mean(xs).getOrElse(0.0) | ||
|
||
mean(xs.map(d => math.pow(meanV - d, 2))) | ||
}) | ||
} | ||
} | ||
|
||
object SolutionP68 extends SolutionP68 |
20 changes: 20 additions & 0 deletions
20
src/test/scala/com/chobostudy/loustler/error/SolutionP68Test.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package com.chobostudy.loustler.error | ||
|
||
import org.scalatest.FunSuite | ||
|
||
/** | ||
* @author loustler | ||
* @since 11/03/2017 21:52 | ||
*/ | ||
class SolutionP68Test extends FunSuite { | ||
test("variance should be correct") { | ||
val seq = List(1.0, 1.1, 1.2, 1.3, 1.4) | ||
val mean = seq.sum / seq.size | ||
val variance = seq.map(d => Math.pow(mean - d, 2)).sum / seq.size | ||
val expect = Option(variance) | ||
|
||
val result = SolutionP68.variance(seq) | ||
|
||
assert(result == expect) | ||
} | ||
} |