using GenDanDoZad;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _05_1_Newton
{
  public partial class Form1 : Form
  {
    Log log;
    double a;
    double x0;
    double eps;
    public Form1()
    {
      InitializeComponent();
      log = new Log(tbLog);
      log.SetFontSize(16);
    }
    void CzytajDane()
    {
      a = double.Parse(textBox1.Text);
      eps = double.Parse(textBox2.Text);
      x0 = double.Parse(textBox3.Text);
    }
    private void button1_Click(object sender, EventArgs e)
    {
      CzytajDane();
      double x = x0;
      double h;
      int licznik = 0;
      do
      {
        licznik++;
        h = -(x * x - a) / (2 * x);
        x = x + h;
        log.l($"Cykl: {licznik}    x: {x}");
      } while (Math.Abs(h) >= eps);
      log.l($"Metoda Newtona: pierwiastek z {a}: {x}    {licznik} iteracji");
      log.l($"Klasa Math:        Math.Sqrt({a}): {Math.Sqrt(a)}");
    }


    delegate double F(double x);


    double ObliczMetodaNewtona(F f, F fp, double x0, double eps)
    {
      double x = x0;
      double h;
      int licznik = 0;
      do
      {
        licznik++;
        h = -f(x) / fp(x);
        x = x + h;
        log.l($"Cykl: {licznik}    x: {x}");
      } while (Math.Abs(h) >= eps);
      return x;
    }


    double fun(double x)
    {
      return x * x - a;
    }
    double funPrim(double x)
    {
      return 2 * x;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      CzytajDane();
      double x = ObliczMetodaNewtona(fun, funPrim, x0, eps);
      log.l($"Metoda Newtona nr 2: pierwiastek z {a}: {x}");
      log.l($"Klasa Math:             Math.Sqrt({a}): {Math.Sqrt(a)}");
    }
  }
}
