// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CSharp; namespace E { public interface IFuncEval { double Eval(double x); } public class FuncEvalFactory { private static int n = 0; private static Dictionary m = new Dictionary(); public static IFuncEval Create(string expr) { IFuncEval o = null; if(m.ContainsKey(expr)) { o = m[expr]; } else { n++; string cn = "FuncEval_" + n; string src = "using System;" + "using E;" + "" + "public class " + cn + " : IFuncEval" + "{" + " public double Eval(double x)" + " {" + " return " + expr + ";" + " }" + "}"; CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.dll"); param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CompilerResults res = comp.CompileAssemblyFromSource(param, src); Assembly asm = res.CompiledAssembly; o = (IFuncEval)asm.CreateInstance(cn); m.Add(expr, o); } return o; } } public struct Point { public double x; public double y; } public class Calc { private const double START = 10; private const double SMALL = 0.0000001; public delegate double func(double x); private static double D1(func f, double x) { return (f(x+SMALL/2) - f(x-SMALL/2)) / SMALL; } public static double FindLocalExtrema(func f) { double x = START; double oldx; do { oldx = x; x = x - f(x) / D1(f,x); } while (Math.Abs(x - oldx) > SMALL); return x; } public static Point TwoFunctionsCross(string expr1, string expr2) { IFuncEval f1 = FuncEvalFactory.Create(expr1); IFuncEval f2 = FuncEvalFactory.Create(expr2); double x0 = FindLocalExtrema(x => f1.Eval(x) - f2.Eval(x)); Point p; p.x = x0; p.y = f1.Eval(x0); return p; } } public class MainClass { public static void Test(string expr1, string expr2) { Console.WriteLine(expr1 + " = " + expr2); Point p = Calc.TwoFunctionsCross(expr1, expr2); Console.WriteLine(p.x + " " + p.y); } public static void Main(string[] args) { Test("x+1", "3-x"); Test("x*x", "7*x+5"); } } }