Search code examples
c#mathdoubleequation

What's wrong in this formula when calculating it with C#?


I need to calculate a value based on a formula that I've checked there, as we can see in this screenshot:

formula and graph

I've tried to this equation in my C# app, but I don't get the expected values.

For example, I've created a basic console app:

public static void Calculate()
{
    var values = new double[] { 1, 0.75, 0.5, 0.25, 0};

    // y = - ((4/3) * x^3) + (3 * x^2) - ((2/3) * x)
    foreach (var value in values)
    {
        var calcul1 = - ((4 / 3) * Math.Pow(value, 3))
                      + (3 * Math.Pow(value, 2))
                      - ((2 / 3) * value);

        var calcul2 = ((-4 / 3) * (value * value * value))
                      + (3 * (value * value))
                      + ((-2 / 3) * value);

        Console.WriteLine($"value: {value} - calcul1: {calcul1} / calcul2: {calcul2}");
    }
}

I get these results, that are not close to the expected results:

value: 1 - calcul1: 2 / calcul2: 2
value: 0.75 - calcul1: 1.265625 / calcul2: 1.265625
value: 0.5 - calcul1: 0.625 / calcul2: 0.625
value: 0.25 - calcul1: 0.171875 / calcul2: 0.171875
value: 0 - calcul1: 0 / calcul2: 0

What's wrong? Is it related to the use of double?


Solution

  • I refactored your code in order to obtain the correct values. If you perform a division calculation without a explicit casting c# Implicitly cast to an integer, discarding the decimal part:

    public static void Calculate()
    {
        var values = new double[] { 1, 0.75, 0.5, 0.25, 0};
    
        // y = - ((4/3) * x^3) + (3 * x^2) - ((2/3) * x)
        foreach (var value in values)
        {
            double firstFraction = (double)4/3;
            double secondFraction = (double)2/3;
            
            var calcul1 = - (firstFraction * Math.Pow(value, 3))
                          + (3 * Math.Pow(value, 2))
                          - (secondFraction * value);
    
            var calcul2 = ((firstFraction*-1) * (value * value * value))
                          + (3 * (value * value))
                          + ((secondFraction*-1) * value);
    
            Console.WriteLine($"value: {value} - calcul1: {calcul1} / calcul2: {calcul2}");
        }
    }