Advertisement
Guest User

Untitled

a guest
Apr 27th, 2015
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. (*
  2. Gauss Siedel Method
  3. Roll no 4167441150
  4. *)
  5. GSiedel[A0_, n0_, x0_, xold0_, it0_, b0_] :=
  6. Module[{A = A0, n = n0, x = x0, xold = xold0, it = it0, b = b0},
  7. Upp = ConstantArray[0, {n, n}];
  8. For[i = 1, i <= n, i++,
  9. For[j = i + 1, j <= n, j++,
  10. Upp[[i, j]] = A[[i, j]];
  11. ];
  12. ];(* Upper triangular matrix *)
  13.  
  14. Dia = ConstantArray[0, {n, n}];
  15. For[i = 1, i <= n, i++,
  16. Dia[[i, i]] = A[[i, i]];
  17. ]; (* Diagonal matrix *)
  18.  
  19. Low = ConstantArray[0, {n, n}];
  20. For[i = 1, i <= n, i++,
  21. For[j = 1, j < i, j++,
  22. Low[[i, j]] = A[[i, j]];
  23. ];
  24. ]; (* Lower triangular matrix *)
  25.  
  26. h = -(Inverse[Low + Dia]).Upp;
  27. c = (Inverse[Low + Dia]).b;
  28.  
  29. (* xk+1=h.xk+c *)
  30. Print["\n\n-------------------OUTPUT-----------------\n"];
  31.  
  32. For[i = 1, i <= it, i++,
  33. xnew = h.xold + c;
  34. Print["Solution at iteration #", i, " :\n"];
  35. For[j = 1, j <= n, j++,
  36. Print[x[[j, 1]], "= ", N[xnew[[j, 1]]]];
  37. ];
  38. Print["\n\n"];
  39. xold = xnew;
  40. ];
  41. ];
  42.  
  43. A = ({
  44. {10, -2, 1},
  45. {-2, 10, -2},
  46. {-2, -5, 10}
  47. });
  48. b = ({
  49. {9},
  50. {12},
  51. {18}
  52. });
  53. x = ({
  54. {x1},
  55. {x2},
  56. {x3}
  57. });
  58. xold = ({
  59. {0},
  60. {0},
  61. {0}
  62. });
  63. GSiedel[A, 3, x, xold, 5, b];
  64.  
  65. NRM[a0_, n_] :=
  66. Module[{x0 = N[a0]},
  67. it = 1;
  68. xold = 1;
  69. xnew = 2;
  70. Print["\n\n----------------------RESULT----------------------\n"]
  71. While[Abs[xold - xnew] != 0,
  72. x1 = x0 - f[x0]/f'[x0];
  73. Print["Root at iteration #", it++, " is: ", NumberForm[x1, 16],
  74. "\t Error= ", Abs[xold - xnew]];
  75. xold = N[x0];
  76. xnew = N[x1];
  77. x0 = x1;
  78. ];
  79. Print["\n\n Hence the root of the given equation is ",
  80. NumberForm[x1, 16]];
  81. ];
  82. f[x_] := -0.9 x^2 + 1.7 x + 2.5;
  83. NRM[0.5, 10];
  84.  
  85. (*
  86. Euler's Method
  87. Roll no 4167441150
  88. *)
  89. Euler[x_, y_, n_, h_] :=
  90. Module[{x0 = N[x], y0 = N[y]},
  91. Print["\n\n------------------OUTPUT--------------------\n"];
  92. For[i = 1, i <= n, i++,
  93. F = f[x0, y0]; (* y'=f(xi,yi) *)
  94. x0 = x0 + h;
  95. y0 = y0 + F*h;
  96. Print["Iteration #", i, ":\t 'x'= ", x0, "\t 'y'= ", y0];
  97. ];
  98. ];
  99. f[x_, y_] := (1 + 4*x)*y^0.5;
  100. Euler[0, 1, , 100, 0.01];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement