Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating a formula with exponents

Tags:

c#

math

formula

I am trying to replicate the following formula from Excel in to a C# app and the result is different.

The answer where x=5 should be y=55.249875 which I have just done using Windows calculator and matches to the Excel answer.. but not when I try it in C#.

For E I use Math.Exp and for x^y I use Math.Pow().

Any ideas?

Formula:

y = -1E-06x^6 + 0.0001x^5 - 0.0025x^4 + 0.0179x^3 + 0.0924x^2 - 0.6204x + 55.07
like image 474
ITManx Ltd Avatar asked Jul 19 '26 09:07

ITManx Ltd


2 Answers

This would be:

static double Compute(double x)
{
    return -1E-06 * Math.Pow(x, 6) 
        + 0.0001 * Math.Pow(x, 5) 
        - 0.0025 * Math.Pow(x, 4) 
        + 0.0179 * Math.Pow(x, 3) 
        + 0.0924 * Math.Pow(x, 2)
        - 0.6204 * x + 55.07;
}

Here is a fully working test program to demonstrate:

using System;
class Test
{
    static double Compute(double x)
    {
        return -1E-06 * Math.Pow(x, 6) 
            + 0.0001 * Math.Pow(x, 5) 
            - 0.0025 * Math.Pow(x, 4) 
            + 0.0179 * Math.Pow(x, 3) 
            + 0.0924 * Math.Pow(x, 2)
            - 0.6204 * x + 55.07;
    }

    static void Main()
    {
        Console.WriteLine("Value for x {0} == {1}", 5, Compute(5));
        Console.ReadKey();
    }
}

I think the confusion was that you were assuming that -1E-06 required Math.Exp, but it does not. This is just a simple number in Scientific Notation.

like image 90
Reed Copsey Avatar answered Jul 20 '26 23:07

Reed Copsey


E is scientific notation and so base 10. Math.Exp is natural exponentiation, i.e. e^x.

Instead of writing -Math.Exp(-06)*Math.Pos(x, 6) you simply write -1E-06*Math.Pow(x, 6).

like image 27
David Heffernan Avatar answered Jul 20 '26 23:07

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!