Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. // AdvPrPa series 1, written by Jämes Ménétrey
  2. // Master in Engineering, University of Applied Sciences and Arts Western Switzerland
  3.  
  4. import scala.annotation.tailrec
  5.  
  6. //
  7. // n-th root estimation
  8. //
  9.  
  10. val epsilon = 0.0001
  11.  
  12. def abs(x: Double) = if (x < 0) -x else x
  13. def isGoodEnough(x: Double, y: Double) = abs(x - y) < epsilon
  14.  
  15. // Only for e in [1;Inf[
  16. def pow(x: Double, e: Int) = {
  17. require(x > 0)
  18.  
  19. 1.to(e).foldLeft[Double](1)((acc, _) => acc * x)
  20. }
  21.  
  22.  
  23. // The square root can be defined as x in x^2 = y. It can be rewritten f(x, y) = x^2 - y and Newton's method
  24. // helps to find the zero of that function, using its partial derivative form on x: f'(x, y) = 2x.
  25. // The problem can be generalized as f(x, y) = x^e - y and f'(x, y) = e * x^(e-1).
  26. def nthRoot(n: Double, e: Int = 2): Double = {
  27. def f(xi: Double) = pow(xi, e) - n
  28. def df(xi: Double) = e * pow(xi, e - 1)
  29.  
  30. @tailrec
  31. def improve(xi: Double): Double = xi - f(xi) / df(xi) match {
  32. case xj if isGoodEnough(xi, xj) => xj
  33. case xj => improve(xj)
  34. }
  35.  
  36. improve(10)
  37. }
  38.  
  39. println(s"Square root of 16: ${nthRoot(16)}")
  40. println(s"4-th root of 16: ${nthRoot(16, 4)}")
  41. println(s"3-th root of 27: ${nthRoot(27, 3)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement