简体   繁体   中英

Wrong return value in Runge Kutta C#

Could someone please tell me, why It always returns the same "y" value? I've searched a lot on the Internet and I still don't know why it is not working.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Inżynierkuuuu
{
class Lecimy
{
    double t, y, krok, cel;

    public Lecimy(double t, double y, double krok, double cel)
    {
        this.t = t;
        this.y = y;
        this.krok = krok;
        this.cel = cel;
    }

    public delegate double funkcja(double t, double y);

    public double RK(double t, double y, double krok, funkcja yp)
    {
        double k1 = krok * yp(t, y);
        double k2 = krok * yp(t + krok * 0.5, y + k1 * 0.5);
        double k3 = krok * yp(t + krok * 0.5, y + k2 * 0.5);
        double k4 = krok * yp(t + krok, y + k3);

        double reszta = 1 / 6 * (k1 + 2 * k2 + 2 * k3 + k4);

        this.y = y + reszta;

        return y;
    }

    public void Run()
    {
        while(t < cel)
        {
            y = RK(t, y, krok, FN1);
            t = t + krok;
            Console.WriteLine("t: {0}, y: {1}", t, y);
        }
    }

    public double FN1(double t, double y)
    {
        return y;
    }

}
}

Second class: The "y" value here is 1, when I change It egto 5, it will always return 5 in the Output window.

static void Main(string[] args)
    {
        Lecimy e = new Lecimy(0.0, 1.0, 0.0001, 1.0); 
        e.Run();
        //Application.EnableVisualStyles();
        //Application.SetCompatibleTextRenderingDefault(false);
        //Application.Run(new Form1());
    }

I have no idea what you want to do, but I'm sure the following line is not what yo want:

double reszta = 1 / 6 * (k1 + 2 * k2 + 2 * k3 + k4);

reszta will always be zero. 1 / 6 is 0 , as both 1 and 6 are integers. Use 1.0 / 6 or something similar.

There are two obvious issues with your code even though I don't understand what you are trying to do.

  1. 1/6 will always be zero, you should be doing 1.0/6 . The reason being that in the former, the /(int, int) overload is chosen.
  2. You are conflating the argument y with the class field y . Do not name a local variable / argument / field with the same name, its confusing and very error prone; in method RK , are you sure you shouldn't be returning this.y ? Are you sure this.y = y + reszta is correct and it shouldn't be this.y += reszta . See how confusing this is?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM