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_2_Newton
{
  public partial class Form1 : Form
  {
    Log log;
    double a;
    double eps;
    double x0;
    public Form1()
    {
      InitializeComponent();
      log = new Log(textBox4);
      log.SetFontSize(18);
    }
    void CzytajDane()
    {
      a = double.Parse(textBox1.Text);
      x0 = double.Parse(textBox2.Text);
      eps = double.Parse(textBox3.Text);
    }
    private void button1_Click(object sender, EventArgs e)
    {
      log.l("................................................................................................");
      CzytajDane();
      double x = x0;
      double h;
      int licznik = 0;
      do
      {
        licznik++;
        h = -(x * x - a) / (2 * x);
        x = x + h;
        log.l($"   Cykl: {licznik}  h: {h}   x: {x}");
      } while (Math.Abs(h) > eps);
      log.l($"Pierwastek z {a}, met Newtona: {x:f18}");
      log.l($"Pierwastek z {a},   Math.Sqrt: {Math.Sqrt(a):f18}");
    }

    delegate double F(double x);

    double fun(double x)
    {
      return x * x - a;
    }
    double funPrim(double x)
    {
      return 2 * 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}  h: {h:f18}   x: {x:f18}");
      } while (Math.Abs(h) > eps);      
      return x;
    }

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