Pregunta

I'm building scientific calculator for school project and have to implement quadratic equatation for functions with x,y in [a,b] So I'm using Accord.Net and Have managed to use it but I want to automate the process..

I have this code:

Func<double, double> function = x => x * x * x + 2 * x * x - 10 * x;
        Accord.Math.Optimization.BrentSearch search = new Accord.Math.Optimization.BrentSearch(function, -4, 3);
        double max = search.Maximize();
        double min = search.Minimize();
        double root = search.FindRoot();

But I need to do something like this:

string temp = Input.Text.ToString();
        Func<double, double> function = x => temp; //doesn't want string, and BrentSearch wants func<double,double>
        Accord.Math.Optimization.BrentSearch search = new Accord.Math.Optimization.BrentSearch(function, -4, 3);
        double max = search.Maximize();
        double min = search.Minimize();
        double root = search.FindRoot();

The thing is that Func don't accept string and BrentSearch wants func

Also the input comes from textbox and user manualy type the function..

Thank you!!!!!!!

¿Fue útil?

Solución

This is not a simple task. You're actually trying to convert user input into C# code - which is essentially the same thing the C# compiler does!

If you want to give it a shot, it is possible to leverage the C# compiler to do the parsing for you.

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Text;
using Microsoft.CSharp;

private static Func<double, double> CompileFunction(string expression)
{
    StringBuilder sourceBuilder = new StringBuilder();
    sourceBuilder.AppendLine("using System;");
    sourceBuilder.AppendLine("using System.Linq.Expressions;");
    sourceBuilder.AppendLine("class ExpressionGenerator{");
    sourceBuilder.AppendLine("public static Func<double, double> Generate(){");
    sourceBuilder.AppendLine("return x => " + expression + ";");
    sourceBuilder.AppendLine("}}");


    Dictionary<string, string> providerOptions = new Dictionary<string, string>();
    providerOptions.Add("CompilerVersion", "v3.5");
    CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
    CompilerParameters parameters = new CompilerParameters(new[] { "System.Core.dll" });
    CompilerResults results = provider.CompileAssemblyFromSource(parameters, sourceBuilder.ToString());
    return (Func<double, double>)results.CompiledAssembly.GetType("ExpressionGenerator").GetMethod("Generate").Invoke(null, null);
}

You can call this function like this:

string input = "x * x";  // Or however you get the input
Func<double, double> myFunction = CompileFunction(input);

You'll still need to handle things like syntax errors in the provided strings, etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top