Search code examples
c#floating-pointdivisioninteger-division

Big numbers in function in windows forms


im trying to do a function graph, its working but for some reason when i display function its giving me big numbers, i dunno why code looks fine to me, maybe i did something wrong with sample that i use. If you, for some reason, want to know what writen in these 3 textbox, here - first one is starting point, second one is end point, and last one is step.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            {
                {
                    double xn = Convert.ToDouble(textBox1.Text);
                    double xk = Convert.ToDouble(textBox2.Text);
                    double xh = Convert.ToDouble(textBox3.Text);
                    if ((xn >= xk) || (xh > (xk - xn))) { MessageBox.Show("Данные заполнены неверно"); }
                    else
                    {
                        double z;
                        double x = xn;
                        while (x <= xk)
                        {
                            if (x <= 0) z = (1 + x) / Math.Pow(1 + Math.Pow(x, 2), 1 / 3);
                            else
                             if (x > 0 && x <= 1) z = -x + Math.Exp(-2 * x);
                            else z = Math.Pow(Math.Abs(2 - x), 1 / 3);
                            chart1.Series[0].Points.AddXY(x, z);
                            x += xh;


                        }

                    }
                }
            }
        }

Mynegga


Solution

  • I believe your problem might be with the division between two integers of 1 / 3 in the expression

    Math.Pow(1 + Math.Pow(x, 2), 1 / 3)
    

    because

    double oneThirdWrong = 1 / 3; // is equal to 0
    

    and you may be expecting

    double oneThirdRight = 1 / (double)3; // is 0.333...
    

    Test Code (in .Net Core 3)

    Console.WriteLine($"One-third wrong {1/3}" );
    Console.WriteLine($"One-third right {1/3.0}" );
    

    enter image description here