Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. import Foundation
  2.  
  3. func f1(_ x: Double, _ y: Double) -> Double {
  4. return cos(y-1) + x - 0.5
  5. }
  6.  
  7. func f2(_ x: Double, _ y: Double) -> Double {
  8. return y - cos(x) - 3
  9. }
  10.  
  11. func f1dx(_ x: Double, _ y: Double) -> Double {
  12. return 1.0
  13. }
  14.  
  15. func f1dy(_ x: Double, _ y: Double) -> Double {
  16. return sin(1-y)
  17. }
  18.  
  19. func f2dx(_ x: Double, _ y: Double) -> Double {
  20. return sin(x)
  21. }
  22.  
  23. func f2dy(_ x: Double, _ y: Double) -> Double {
  24. return 1.0
  25. }
  26.  
  27. func calculateM(_ x: Double, _ y: Double) -> Double {
  28. let wf1 = (f1dx(x,y) * f1dx(x,y) + f1dy(x,y)*f1dy(x,y)) * f1(x,y)
  29. +
  30. (f1dx(x,y) * f2dx(x,y) + f1dy(x,y) * f2dy(x,y)) * f2(x,y)
  31.  
  32. let wf2 = (f1dx(x,y) * f2dx(x,y) + f1dy(x,y) * f2dy(x,y)) * f1(x,y)
  33. +
  34. (f2dx(x,y) * f2dx(x,y)+f2dy(x,y) * f2dy(x,y)) * f2(x,y)
  35.  
  36. return (f1(x,y) * wf1+f2(x,y) * wf2)
  37. /
  38. (wf1 * wf1 + wf2 * wf2)
  39. }
  40.  
  41.  
  42.  
  43. var epsilon = 0.0
  44. let maxEpsilon = 0.001
  45. var iteration = 0
  46. var w: [Double] = [10, 30]
  47.  
  48. repeat {
  49. let m = calculateM(w[0], w[1])
  50. var wNew: [Double] = [0, 0]
  51.  
  52. wNew[0] = w[0] - m * (f1dx(w[0], w[1]) * f1(w[0],w[1]) + f2dx(w[0],w[1]) * f2(w[0], w[1]))
  53. wNew[1] = w[1] - m * (f1dy(w[0], w[1]) * f1(w[0],w[1]) + f2dy(w[0],w[1]) * f2(w[0], w[1]))
  54.  
  55.  
  56. if fabs(w[0] - wNew[0]) > fabs(w[1] - wNew[1]) {
  57. epsilon = fabs(w[0] - wNew[0])
  58. } else {
  59. epsilon = fabs(w[1] - wNew[1])
  60. }
  61.  
  62. w[0] = wNew[0]
  63. w[1] = wNew[1]
  64. iteration += 1
  65.  
  66. print("nIteration №(iteration)")
  67. print("x = (w[0]) y = (w[1])")
  68. print("Accuracy = (epsilon)")
  69. } while epsilon >= maxEpsilon
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement