Form1.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using GenDanDoZad;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace _05_1_Newton
  12. {
  13. public partial class Form1 : Form
  14. {
  15. Log log;
  16. double a;
  17. double x0;
  18. double eps;
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. log = new Log(tbLog);
  23. log.SetFontSize(16);
  24. }
  25. void CzytajDane()
  26. {
  27. a = double.Parse(textBox1.Text);
  28. eps = double.Parse(textBox2.Text);
  29. x0 = double.Parse(textBox3.Text);
  30. }
  31. private void button1_Click(object sender, EventArgs e)
  32. {
  33. CzytajDane();
  34. double x = x0;
  35. double h;
  36. int licznik = 0;
  37. do
  38. {
  39. licznik++;
  40. h = -(x * x - a) / (2 * x);
  41. x = x + h;
  42. log.l($"Cykl: {licznik} x: {x}");
  43. } while (Math.Abs(h) >= eps);
  44. log.l($"Metoda Newtona: pierwiastek z {a}: {x} {licznik} iteracji");
  45. log.l($"Klasa Math: Math.Sqrt({a}): {Math.Sqrt(a)}");
  46. }
  47. delegate double F(double x);
  48. double ObliczMetodaNewtona(F f, F fp, double x0, double eps)
  49. {
  50. double x = x0;
  51. double h;
  52. int licznik = 0;
  53. do
  54. {
  55. licznik++;
  56. h = -f(x) / fp(x);
  57. x = x + h;
  58. log.l($"Cykl: {licznik} x: {x}");
  59. } while (Math.Abs(h) >= eps);
  60. return x;
  61. }
  62. double fun(double x)
  63. {
  64. return x * x - a;
  65. }
  66. double funPrim(double x)
  67. {
  68. return 2 * x;
  69. }
  70. private void button2_Click(object sender, EventArgs e)
  71. {
  72. CzytajDane();
  73. double x = ObliczMetodaNewtona(fun, funPrim, x0, eps);
  74. log.l($"Metoda Newtona nr 2: pierwiastek z {a}: {x}");
  75. log.l($"Klasa Math: Math.Sqrt({a}): {Math.Sqrt(a)}");
  76. }
  77. }
  78. }