Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to find the maximum and minimum value of a function #94

Open
pomaton12 opened this issue Dec 24, 2023 · 3 comments
Open

how to find the maximum and minimum value of a function #94

pomaton12 opened this issue Dec 24, 2023 · 3 comments
Labels
needs author feedback Needs feedback from the author to be closed or worked on.

Comments

@pomaton12
Copy link

Hello, is there a way to calculate the maximum value and the minimum value of a function declared in string function = "x^2 +2" within a range 0 - 10

@gumbarros
Copy link
Member

Merry Christmas🎅🎄

Is this snippet what you need?

using NCalc;

string function = "x^2 + 2";

Expression expression = new(function);


double maxValue = double.MinValue;
double maxArg = 0;
double minValue = double.MaxValue;
double minArg = 0;

for (double x = 0; x <= 10; x++)
{
    expression.Parameters["x"] = x;
    var result = Convert.ToDouble(expression.Evaluate());

    if (result > maxValue)
    {
        maxValue = result;
        maxArg = x;
    }

    if (result < minValue)
    {
        minValue = result;
        minArg = x;
    }
}

Console.WriteLine($"Maximum value: {maxValue} at x = {maxArg}");
Console.WriteLine($"Minimum value: {minValue} at x = {minArg}");
image

@Bykiev
Copy link
Contributor

Bykiev commented Mar 20, 2024

You can also use array parameters like this:

var e = new Expression("x * x", EvaluateOptions.IterateParameters);
e.Parameters["x"] = new [] { 0, 1, 2, 3, 4 };
var result = (IList)e.Evaluate();
Assert.AreEqual(0, result[0]);
Assert.AreEqual(1, result[1]);
Assert.AreEqual(4, result[2]);
Assert.AreEqual(9, result[3]);
Assert.AreEqual(16, result[4]);

@gumbarros gumbarros added the needs author feedback Needs feedback from the author to be closed or worked on. label Apr 22, 2024
@gumbarros
Copy link
Member

@pomaton12 feel free to close the issue if your problem is solved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs author feedback Needs feedback from the author to be closed or worked on.
Projects
None yet
Development

No branches or pull requests

3 participants