Search code examples
c#mathmathematical-optimizationdiscrete-mathematicspolynomial-math

How can I use the following formula to determine the value of a variable?


How can I use the following formula to determine the value of a variable?

Before someone suggests this is off topic, I am not on Stack-overflow to determine what formula to use. I am here so I can figure out how to utilise the formula via c#.

Background:

I had previously opened a thread on math.stackexchange.com so someone there could help me generate a forumla which would create the following sequence: 1 , 7 , 14, 30. A user there called "Half-Blood prince" suggested I use the below formula to generate this sequence

an=A*n^3+B*n^2+C*n+D 

I have in the past used int, double etc. then within a loop say int i = i*7; but obviously in this case the mathematical forumla is alittle more complicated, so I'm here to ask how can I utilise the above whithin C#

Link to thread: https://math.stackexchange.com/questions/985704/what-is-the-formula-to-generate-this-number-sequence-1-7-14-30


Solution

  • You could use that equation in C# like so:

    public static double Calculate(double n)
    {
        return (1.33*(n*n*n)) - (7.5 * (n*n)) + (19.16 * n) - 12;
    }
    

    And call it with

    Console.WriteLine(Calculate(1)); 
    Console.WriteLine(Calculate(2)); 
    Console.WriteLine(Calculate(3)); 
    Console.WriteLine(Calculate(4)); 
    

    The above writes

    0.99
    6.96
    13.89
    29.76

    Which is your required sequence, if you rounded each result to an integer.

    Live example: http://rextester.com/TIU97590