public void MathFunctionOfSinReturns1ForPiHalfConstant() { IExpression piHalf = new Constant(Math.PI / 2.0); IExpression mathFun = new MathFunction(Math.Sin, piHalf); Assert.AreEqual(1.0, mathFun.Interpret(new Context(3)), 1e-5); }
public double Solve(Equasion eq, double a, double b) { MathFunction func = eq.Left - eq.Right; if (func.Calculate(a) * func.Calculate(b) > 0) { throw new Exception("Method cannot be applied!"); } if (Math.Abs(func.Calculate(a)) <= epsilanIter) { return(a); } if (Math.Abs(func.Calculate(b)) <= epsilanIter) { return(b); } double xn = (a + b) / 2; while (Math.Abs(func.Calculate(xn)) > epsilanIter) { if (func.Calculate(xn) * func.Calculate(a) < 0) { b = xn; } else if (func.Calculate(xn) * func.Calculate(b) < 0) { a = xn; } xn = (a + b) / 2; } return(xn); }
private void SaveResults() { lock (saveResultsObj) { wtch.Stop(); if (resultsSaved) { return; } string resultsFileName = resultTextBox.Text != "" ? resultTextBox.Text : "results.txt"; WriteLog(LogFormats.SavingResultsInto(resultsFileName)); var result = new MathFunction <BigFloat>(1.0, NumericalAnalysisLibrary.Functions.Generic.MathFunctionType.Sum, proccessedFunctions.ToArray()); StreamWriter results = new StreamWriter(resultsFileName); results.WriteLine("Function to express y = {0}\n" + "Function expression by point x = {1}, power = {2}\n" + "y = {3}", function, pointOfExpression, powerOfExpression, result); Invoke(new Method(() => MessageBox.Show(string.Format("Function to express y = {0}\n" + "Function expression by point x = {1}, power = {2}\n" + "y = {3}", function, pointOfExpression, powerOfExpression, result)))); results.WriteLine("Time spent: {0}", wtch.Elapsed); results.Close(); resultsSaved = true; } }
public GraphicsPath PathForRectangularMethod(MathFunction func, RectangularMethodType type, double a, double b, int n) { GraphicsPath path = new GraphicsPath(); double difference = (b - a) / n; for (int i = 0; i < n; i++) { double x = 0; switch (type) { case RectangularMethodType.Left: x = a + difference * i; break; case RectangularMethodType.Right: x = a + difference * (i + 1); break; case RectangularMethodType.Central: x = a + difference * (i + 0.5); break; default: break; } path.AddRectangle(new RectangleF((float)FunctionXToScreenX(a + difference * i), (float)FunctionYToScreenY(func.Calculate(x)), (float)FunctionXToScreenX(x + difference) - (float)FunctionXToScreenX(x), (float)FunctionYToScreenY(0) - (float)FunctionYToScreenY(func.Calculate(x)))); } return(path); }
private void Draw(DrawingSettings drSet) { if (context == null) { return; } if (drSet.drawingObject is MathFunction) { MathFunction func = drSet.drawingObject as MathFunction; Tuple <double, double>[] continuousRegions = func.ContinuousRegions(minX, maxX, minY, maxY); foreach (Tuple <double, double> region in continuousRegions) { PointF[] points = PointsForFunction(func, region.Item1, region.Item2); context.DrawLines(new Pen(drSet.borderColor, drSet.borderWidth), points); } } else if (drSet.drawingObject is GraphicsPath) { GraphicsPath path = drSet.drawingObject as GraphicsPath; context.FillPath(drSet.brush, path); context.DrawPath(new Pen(drSet.borderColor, drSet.borderWidth), path); } }
public static void RowTransparentRoughness(int spp) { Material CreateMaterial() { var material = new Material(); var color = new Color(1f, 1f, 1f); material.Texture = SolidColor.Create(color); material.SpecularColor = new Color(0.8f, 0.8f, 0.8f); material.Transparency = 0.92f; material.Metallic = 0.65f; material.RefractiveIndex = 1.51f; material.Ambient = 0f; return(material); } const float delta = 1f / 9; RowTestByDelegate(spp, "transparent_roughness", i => { var metal = CreateMaterial(); metal.Roughness = MathFunction.Saturate((i - 1) * delta); return(metal); }); }
static void Main(string[] args) { // f is a math function with double argument, returning a double // one way to initialise f MathFunction f = new MathFunction(Math.Sin); // or simply by setting f = Math.Cos; // use it Console.WriteLine("01) f(pi)=" + f(Math.PI)); var values = new double[] { 0, 1 * Math.PI, 2 * Math.PI }; WriteValues(values, "sin", Math.Sin); WriteValues(values, "cos", Math.Cos); // delegates can be collected (+= op), such as Event-Handlers // Lambda-Expression-Syntax, preview, see exercise double a = 2.0; MathFunction g = x => 1.0 - a / (x * x); MathFunction dg = x => 2 * a / (x * x * x); // Console.WriteLine("03) sqrt 2=..."); // double y = Newton(3, 1.5, g, dg); // Console.WriteLine($"04) sqrt 2={y}"); }
/* * static void Main(string[] args) * { * string email = "*****@*****.**"; * * Console.WriteLine(email); * * bool IsValid = Validate(1, ref email); * * Console.WriteLine(email); * Console.ReadKey(); * } * * * private static bool Validate(int employeeId, ref string email) * { * email = "*****@*****.**"; * return true; * } */ /* * static void Main(string[] args) * { * IMathFunction mathFunction = new MathFunction(); * ExecuteMathOperation executeMathOperation; * Console.WriteLine("We are going to perform mathematical operation:"); * * while (true) * { * Console.WriteLine("Allowed keys are:"); * Console.WriteLine("+"); * Console.WriteLine("-"); * Console.WriteLine("*"); * Console.WriteLine("/"); * Console.WriteLine("Use an other key to exit"); * * ConsoleKeyInfo keyInfo = Console.ReadKey(); * * int mode = 1; * * switch (keyInfo.KeyChar) * { * case '+': * executeMathOperation = new ExecuteMathOperation(mathFunction.Add); * mode = 1; * break; * * case '-': * // executeMathOperation = new ExecuteMathOperation(mathFunction.Substract); * mode = 2; * break; * * case '*': * // executeMathOperation = new ExecuteMathOperation(mathFunction.Multiply); * break; * * case '/': * //executeMathOperation = new ExecuteMathOperation(mathFunction.Divide); * break; * * * default: * return; * } * * * Console.WriteLine("First number:"); * string firsrNUmber = Console.ReadLine(); * double numericFirstNumber = Convert.ToDouble(firsrNUmber); * * Console.WriteLine("Second number:"); * string secondNUmber = Console.ReadLine(); * double numericSecondNumber = Convert.ToDouble(secondNUmber); * * switch (mode) * { * case 1: * mathFunction.Add(numericFirstNumber, numericSecondNumber); * break; * } * * Console.WriteLine("Result: {0}", executeMathOperation(numericFirstNumber, numericSecondNumber)); * } * * * } */ //Calling Static function /* * public delegate void LogHandler(string message); * static void LogToConsole(string message) * { * Console.WriteLine("{0} - {1}",DateTime.Now, message); * } * static void Main(string[] args) * { * * LogHandler logHandler = new LogHandler(LogToConsole); * * logHandler("Sample Log"); * Console.ReadKey(); * } * */ //Multi cast delegate /* * public delegate void LogHandler(string message); * static void LogToConsole(string message) * { * Console.WriteLine("{0} - {1}",DateTime.Now, message); * } * * static void LogToFile(string message) * { * message = string.Format("{0} - {1}", DateTime.Now, message); * using (System.IO.StreamWriter file = * new System.IO.StreamWriter(string.Format(@"{0}\log.txt", Environment.CurrentDirectory),true)) * { * file.WriteLine(message); * } * } * * static void Main(string[] args) * { * LogHandler logHandler = null; * logHandler += LogToConsole; * logHandler += LogToFile; * //logHandler -= LogToFile; * * logHandler("Sample Log"); * Console.ReadKey(); * } * */ //simple event /* * static void LogToConsole(string message) * { * Console.WriteLine("{0} - {1}",DateTime.Now, message); * } * * static void LogToFile(string message) * { * message = string.Format("{0} - {1}", DateTime.Now, message); * using (System.IO.StreamWriter file = * new System.IO.StreamWriter(string.Format(@"{0}\log.txt", Environment.CurrentDirectory), true)) * { * file.WriteLine(message); * } * } * static void Main(string[] args) * { * BusinessLogic.Employee employee = new BusinessLogic.Employee(); * // Subscribe the Functions Logger and fl.Logger * employee.Log += new BusinessLogic.Employee.LogHandler(LogToConsole); * employee.Log += new BusinessLogic.Employee.LogHandler(LogToFile); * employee.Login(); * Console.ReadKey(); * } */ //time event /* * public static void Main() * { * // Create a new clock * Clock theClock = new Clock(); * * // Create the display and tell it to * // subscribe to the clock just created * DisplayClock dc = new DisplayClock(); * dc.Subscribe(theClock); * * // Create a Log object and tell it * // to subscribe to the clock * LogClock lc = new LogClock(); * lc.Subscribe(theClock); * * * // Get the clock started * theClock.Run(); * } */ //Data Modeliing /* * public static void Main(string[] args) * { * IEmployee[] employees = new IEmployee[4]; * * employees[0] = new OrganizationModels.Hr(1) * { * Name = "Hr 1", * Email = "*****@*****.**", * Department = DepartmentType.HumanResource, * Salary = 60000 * }; * * employees[1] = new OrganizationModels.Manager(2) * { * Name = "Manager 1", * Email = "*****@*****.**", * Department = DepartmentType.HumanResource, * Salary = 80000, * HrManager = (IHr)employees[0] * }; * * employees[2] = new OrganizationModels.Employee(3) * { * Name = "Employee 1", * Email = "*****@*****.**", * Department = DepartmentType.HumanResource, * Salary = 40000, * HrManager = (IHr)employees[0], * ReportingManager = (IManager)employees[1] * }; * * employees[3] = new OrganizationModels.Employee(4) * { * Name = "Employee 2", * Email = "*****@*****.**", * Department = DepartmentType.HumanResource, * Salary = 50000, * HrManager = (IHr)employees[0], * ReportingManager = (IManager)employees[1] * }; * * * // Assigning Subordinates to Manager * ((IManager)employees[1]).Subordinates = new IEmployee[2]; * ((IManager)employees[1]).Subordinates[0] = employees[2]; * ((IManager)employees[1]).Subordinates[1] = employees[3]; * * // Assigning Employee to Hr * ((IHr)employees[0]).Employees = new IEmployee[3]; * ((IHr)employees[0]).Employees[0] = employees[1]; * ((IHr)employees[0]).Employees[1] = employees[2]; * ((IHr)employees[0]).Employees[2] = employees[3]; * } */ public static void Main() { MathFunction math = new MathFunction(); math.Add(1.5, 2.6); math.Ave(2, 3); }
public void AssignOperation(MathOperations operation) { switch (operation) { case MathOperations.Addition: // we can use anonymous delegate function = delegate(int a, int b) { return(a + b); }; break; case MathOperations.Subtraction: // we can also use lambda expression syntax function = (int a, int b) => { return(a - b); }; break; case MathOperations.Multiplication: // lambda expressions can use parameter type inference for more readability // and obviously also body expressions function = (a, b) => a * b; break; case MathOperations.Division: // unfortunately we cannot convert Func into our custom delegate even if the signature matches // Func<int, int, int> myFunc = (a, b) => a / b; // function = (MathFunction)myFunc; // error function = (a, b) => a / b; break; } }
public LightMathFunctionDataFieldInfo(DataEntityMapping mapping, MathFunction function, params object[] argsObjects) : base(mapping) { if (argsObjects == null || argsObjects.Length == 0) { throw new ArgumentNullException(nameof(argsObjects)); } if (function == MathFunction.Atan2 || function == MathFunction.Max || function == MathFunction.Min || function == MathFunction.Pow) { if (argsObjects.Length != 2) { throw new ArgumentNullException(nameof(argsObjects)); } } if (function == MathFunction.Log || function == MathFunction.Round) { if (argsObjects.Length > 2) { throw new ArgumentNullException(nameof(argsObjects)); } } _function = function; _argsObjects = argsObjects; }
public static GameObject CreateSurface(MathFunction func, double step, int numSteps, CoordinateType coordinateType) //func is a delegate, CoordinateType is an enum { GameObject go = new GameObject("Plane"); MeshFilter mf = go.AddComponent(typeof(MeshFilter)) as MeshFilter; MeshRenderer mr = go.AddComponent(typeof(MeshRenderer)) as MeshRenderer; Mesh m = new Mesh(); m.vertices = new Vector3[(numSteps * 2 + 1) * (numSteps * 2 + 1)]; for (int i = 0; i <= numSteps * 2; i++) { for (int j = 0; j <= numSteps * 2; j++) { if (coordinateType == CoordinateType.Cartesian) { double x = (i - numSteps) * step; double y = (j - numSteps) * step; m.vertices[(numSteps * 2 * i) + j] = new Vector3((float)x, (float)y, (float)func(x, y)); } else if (coordinateType == CoordinateType.Cylindrical) { double r = (i - numSteps) * step; double theta = j * 2 * Math.PI / numSteps; m.vertices[(numSteps * 2 * i) + j] = new Vector3((float)(r * Math.Cos(theta)), (float)(r * Math.Sin(theta)), (float)(func(r, theta))); } else if (coordinateType == CoordinateType.Spherical) { double phi = j * Math.PI / numSteps; double theta = j * 2 * Math.PI / numSteps; m.vertices[(numSteps * 2 * i) + j] = new Vector3((float)(func(phi, theta) * Math.Sin(phi) * Math.Cos(theta)), (float)(func(phi, theta) * Math.Sin(phi) * Math.Sin(theta)), (float)(func(phi, theta) * Math.Cos(phi))); } } } int numQuads = numSteps * numSteps * 4; m.uv = new Vector2[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 0), new Vector2(1, 1) }; m.triangles = new int[6 * numQuads]; int iter = 0; for (int i = 0; i < numSteps * 2; i++) { for (int j = 0; j < numSteps * 2; j++) { m.triangles[iter++] = (numSteps * 2 * i) + j; m.triangles[iter++] = (numSteps * 2 * (i + 1)) + j; m.triangles[iter++] = (numSteps * 2 * (i + 1)) + (j + 1); m.triangles[iter++] = (numSteps * 2 * i) + j; m.triangles[iter++] = (numSteps * 2 * i) + (j + 1); m.triangles[iter++] = (numSteps * 2 * (i + 1)) + (j + 1); } } mf.mesh = m; m.RecalculateBounds(); m.RecalculateNormals(); return(go); }
static void Main(string[] args) { int[] numbers = { 3, 8, 12, 78, 91, 23, 45, 98, 17, 2, 1 }; HelloFunction hf = HelloGerman; hf += HelloEnglish; hf += HelloHungarian; //hf -= HelloGerman; //hf -= HelloEnglish; //hf -= HelloHungarian; hf?.Invoke("John"); // =============================================================================== Console.WriteLine(); MathFunction mf = SUM; mf += Average; // double? result = mf?.Invoke(number); double?[] result = new double?[2]; int pointer = 0; foreach (MathFunction item in mf.GetInvocationList()) { Console.WriteLine(result[pointer++] = item?.Invoke(numbers)); ; } }
private void InitializeDataGridView(MathFunction func, KeyValuePair <double, double>[] result) { DataGridViewColumn xCol = new DataGridViewColumn(), approximationCol = new DataGridViewColumn(), accurateCol = new DataGridViewColumn(); ConfigureColumn(ref xCol, xString); ConfigureColumn(ref approximationCol, approximateY); ConfigureColumn(ref accurateCol, accurateY); dataGridView1.Columns.Add(xCol); dataGridView1.Columns.Add(approximationCol); dataGridView1.Columns.Add(accurateCol); for (int i = 0; i < result.Length; i++) { var newRow = new DataGridViewRow(); newRow.HeaderCell.Value = i.ToString(); for (int j = 0; j < 3; j++) { newRow.Cells.Add(new DataGridViewTextBoxCell()); } newRow.Cells[0].Value = Math.Round(result[i].Key, digitsAfterComma); newRow.Cells[1].Value = Math.Round(result[i].Value, digitsAfterComma); newRow.Cells[2].Value = Math.Round(func.Calculate(result[i].Key), digitsAfterComma); dataGridView1.Rows.Add(newRow); } }
// Simpson's Rule approximation of the integral of a function public static double Integrate(MathFunction f, double a, double b, int stepSize = NUMERICAL_INTEGRATION_RESOLUTION) { stepSize = (stepSize % 2 == 1) ? stepSize + 1 : stepSize; var h = (b - a) / stepSize; var s = f(a) + f(b); Task <double> odds = Task <double> .Factory.StartNew(() => { var t = 0.0; for (var i = 1; i < stepSize; i += 2) { t += 4 * f(a + i *h); } return(t); }); Task <double> evens = Task <double> .Factory.StartNew(() => { var t = 0.0; for (var i = 2; i < stepSize - 1; i += 2) { t += 2 * f(a + i *h); } return(t); }); s = odds.Result + evens.Result; return(s * h / 3); }
public static Graph IterateMathFunction(MathFunction func, double start, double end, double step) { Graph gr = new Graph(); for (double x = start; x < end; x += step) gr.AddPoint(x, func(x)); return gr; }
public void MathFunctionOfSqrtReturnsCorrectValueFor2() { IExpression argument = new VariableX(); IExpression mathFun = new MathFunction(Math.Sqrt, argument); Assert.AreEqual(Math.Sqrt(2.0), mathFun.Interpret(new Context(2))); }
static void Main(string[] args) { MathFunction <BigFloat> function = null; Tuple <int, double> task = null; Console.WriteLine("Input host address:"); host = Console.ReadLine(); Console.WriteLine("Input port number:"); socketPort = Convert.ToInt32(Console.ReadLine()); var r = new BigFloat(double.MaxValue); ConnectToSocket(socketPort, host); function = ReceiveFunctionFromSocket(); int curPower = 0; try { while ((task = ReceiveTaskFromSocket()) != null) { Console.WriteLine(task); SendMessageFromSocket(task, CalculateFunction(task.Item1, task.Item2, ref function, ref curPower)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.ReadKey(); DisconnectFromSocket(); }
public void TestDifferentiate() { MathFunction f = Math.Exp; MathFunction Df = Math.Exp; Assert.Equal(Df(-5), NumericalTools.Differentiate(f)(-5), 2); Assert.Equal(Df(-1), NumericalTools.Differentiate(f)(-1), 2); Assert.Equal(Df(0), NumericalTools.Differentiate(f)(0), 2); Assert.Equal(Df(1), NumericalTools.Differentiate(f)(1), 2); Assert.Equal(Df(5), NumericalTools.Differentiate(f)(5), 2); f = Math.Sin; Df = Math.Cos; Assert.Equal(Df(-5), NumericalTools.Differentiate(f)(-5), 2); Assert.Equal(Df(-1), NumericalTools.Differentiate(f)(-1), 2); Assert.Equal(Df(0), NumericalTools.Differentiate(f)(0), 2); Assert.Equal(Df(1), NumericalTools.Differentiate(f)(1), 2); Assert.Equal(Df(5), NumericalTools.Differentiate(f)(5), 2); f = x => Math.Pow(x, 3); Df = x => 3 * Math.Pow(x, 2); Assert.Equal(Df(-5), NumericalTools.Differentiate(f)(-5), 2); Assert.Equal(Df(-1), NumericalTools.Differentiate(f)(-1), 2); Assert.Equal(Df(0), NumericalTools.Differentiate(f)(0), 2); Assert.Equal(Df(1), NumericalTools.Differentiate(f)(1), 2); Assert.Equal(Df(5), NumericalTools.Differentiate(f)(5), 2); }
public void IntgTest() { MathFunction f1 = square; double result = DefiniteIntegral(sine, 0, Math.PI / 4, 1E-9); double actual = 1 - 1 / Math.Sqrt(2); Assert.True(Math.Abs(result - actual) <= 1E-6); }
//double Integral(double a, double b, double h, MathFunction f) ... //double Newton(double x0, MathFunction f, MathFunction df, double eps) ... /// <summary> /// applies all values to f and writes the results /// </summary> static void WriteValues(double[] values, string name, MathFunction f) { Console.WriteLine($"02) {name}:"); foreach (var v in values) { Console.WriteLine($" {v} -> {f(v)}"); } }
public double LOperator(MathFunction yx, double x) { MathFunction der2 = yx.Derivative(2), der1 = yx.Derivative(1); return(der2.Calculate(x) + PX.Calculate(x) * der1.Calculate(x) + QX.Calculate(x) * yx.Calculate(x)); }
/// <summary> /// </summary> /// <param name="z"> /// Math function to be approximated by Hermite spline. /// MathFunction z is delegate to method with two doubles as attributes, which returns double. /// </param> /// <param name="dx">Partial differentiation with respect to first variable.</param> /// <param name="dy">Partial differentiation with respect to second variable.</param> /// <param name="dxy">Partial differentiation with respect to both variables.</param> public InterpolativeMathFunction(MathFunction z, MathFunction dx, MathFunction dy, MathFunction dxy) { Z = z; Dx = dx; Dy = dy; Dxy = dxy; }
public Operator(char name, MathFunction func, int param, int precedence, Associative assoc) { Name = name; Function = func; Precevendce = precedence; Assoc = assoc; Parameters = param; }
/* */ static void Main(string[] args) { IMathFunction mathFunction = new MathFunction(); ExecuteMathOperation executeMathOperation; Console.WriteLine("We are going to perform mathematical operation:"); while (true) { Console.WriteLine("Allowed keys are:"); Console.WriteLine("+"); Console.WriteLine("-"); Console.WriteLine("*"); Console.WriteLine("/"); Console.WriteLine("Use an other key to exit"); ConsoleKeyInfo keyInfo = Console.ReadKey(); switch (keyInfo.KeyChar) { case '+': executeMathOperation = new ExecuteMathOperation(mathFunction.Add); break; case '-': executeMathOperation = new ExecuteMathOperation(mathFunction.Substract); break; case '*': executeMathOperation = new ExecuteMathOperation(mathFunction.Multiply); break; case '/': executeMathOperation = new ExecuteMathOperation(mathFunction.Devide); break; default: return; } Console.WriteLine("First number:"); string firsrNUmber = Console.ReadLine(); double numericFirstNumber = Convert.ToDouble(firsrNUmber); Console.WriteLine("Second number:"); string secondNUmber = Console.ReadLine(); double numericSecondNumber = Convert.ToDouble(secondNUmber); Console.WriteLine("Result: {0}", executeMathOperation(numericFirstNumber, numericSecondNumber)); } }
protected MathFunction IterationFunc(MathFunction func, double a, double b) { double min = func.MinValue(a, b), max = func.MaxValue(a, b); int k = func.IsGreaterThanZero(a, b) ? -1 : 1; return(k * 2.0 / (min + max)); }
public MathFunc(double x, double y, double z, MathFunction func) { Inputs.Add(x); Inputs.Add(y); Inputs.Add(z); SimulationFunction = func; Outputs.Add(SimulationFunction(Inputs.ToArray())); }
public MathFunc(double x, double y, double z) { Inputs.Add(x); Inputs.Add(y); Inputs.Add(z); SimulationFunction = SimulationFunctions.TestFunc; Outputs.Add(SimulationFunction(Inputs.ConvertAll(item => (double)item).ToArray())); }
static void Main(string[] args) { Console.WriteLine("Class library. Math."); int x = 2, y = 5; Console.WriteLine($"{x} в степени {y} ={MathFunction.Pow(x,y)}\nФакториал {y}={MathFunction.Factorial(y)}"); Console.ReadKey(); }
public static EvolutionInfo GetEvolutionInfo(string parameters, string result) { CoordInfo Seq = GetSequence(parameters, result); MathFunction[] Operators = new MathFunction[] { new Plus(), new Subtract(), new Multiply(), new Divide(), new PowerOf(), new Root(), new Exponent(), new NaturalLog(), new Log(), new Modulos(), new Floor(), new Ceil(), new Round(), new Sin(), new Cos(), new Tan(), new ASin(), new ACos(), new ATan(), new Parentheses(), new Absolute(), //new AND(), //new NAND(), //new OR(), //new NOR(), //new XOR(), //new XNOR(), //new NOT() }; return(new EvolutionInfo( Seq, // Sequence 40, // MaxSize 5, // MaxChange 30000, // CandidatesPerGen 102, // NumberRangeMax 0, // NumberRangeMin 1, // SpeciesAmount 100, // MaxStuckGens 0.8, // EvolvedCandidatesPerGen 0, // RandomCandidatesPerGen 0.2, // SmartCandidatesPerGen Operators // Operatres that can be used in an equation )); }
// Find the inverse of a function public static MathFunction Inverse(MathFunction f, double min = -0x100000000, double max = 0x100000000) // 2^32 { try { return(y => FindRoot(x => f(x) - y, min, max)); } catch (ArgumentException) { throw new ArgumentException("No inverse in specified range"); } }
public static double DefiniteIntegral(MathFunction f, double l, double u, double dx = 1E-9) { double S = 0; for (double x = l; x <= u; x += dx) { S += f(x) * dx; } return(S); }
public void AddOperator(char name, MathFunction func, int parameters = 2, int precedence = 2, Associative assoc = Associative.Left) { if (new[] { '(', ')', ',' }.Contains(name)) { throw new MathOperatorException("Unable to add operators named '(', ')' or ','"); } var op = new Operator(name, func, parameters, precedence, assoc); Operators.Add(name, op); }
public override MathFunction InterpretMathDifferentiation(params string[] respectToVariables) { var diff = Interpret(); for (var i = 0; i < respectToVariables.Length; i++) { var respectTo = Variables.IndexOf(respectToVariables[i]); diff = new MathFunction (Differentiate.FirstPartialDerivativeFunc (new Func<double[], double>(diff), respectTo)); } return diff; }
/// <summary> /// All required derivations are calculated automatically. /// </summary> /// <param name="z"> /// Math function to be approximated by Hermite spline. /// MathFunction z is delegate to method with two doubles as attributes, which returns double. /// </param> public InterpolativeMathFunction(MathFunction z) { Z = z; Dx = new MathFunction (Differentiate.FirstPartialDerivativeFunc (new Func<double[], double>(z), 0)); Dy = new MathFunction (Differentiate.FirstPartialDerivativeFunc (new Func<double[], double>(z), 1)); Dxy = new MathFunction (Differentiate.FirstPartialDerivativeFunc (new Func<double[], double>(Dx), 1)); }
public MathFunctionSurface(SurfaceDimension uDimension, SurfaceDimension vDimension, MathFunction function, Derivation derivation = Derivation.Zero) { Derivation = derivation; if (derivation != Derivation.Zero) { var interpolativeFunction = new InterpolativeMathFunction(function); switch (Derivation) { case Derivation.X: function = interpolativeFunction.Dx; break; case Derivation.Y: function = interpolativeFunction.Dy; break; case Derivation.XY: function = interpolativeFunction.Dxy; break; case Derivation.SecondXY: function = new InterpolativeMathFunction( interpolativeFunction.Dxy).Dxy; break; } } UDimension = uDimension; VDimension = vDimension; var uCount_min_1 = uDimension.KnotCount - 1; //surface.UKnotsCount-1; var vCount_min_1 = vDimension.KnotCount - 1; //surface.VKnotsCount-1; var segments = new List<ISurface>(uCount_min_1*vCount_min_1); for (var i = 0; i < uCount_min_1; i++) { for (var j = 0; j < vCount_min_1; j++) { var segment = CreateSegment(i, j, function); segments.Add(segment); } } Segments = segments; }
public static void CreateMathFunctionRasterDataset() { //Create the Raster Function object and Function Arguments object for first operation IRasterFunction rasterFunction1 = new MathFunction(); IMathFunctionArguments mathFunctionArguments1 = new MathFunctionArguments() as IMathFunctionArguments; //Specify operation to be "Plus" for the first operation mathFunctionArguments1.Operation = esriGeoAnalysisFunctionEnum.esriGeoAnalysisFunctionPlus; //Specify input rasters to the operation IRasterDataset ras01 = OpenRasterDataset("c:\\data\\test", "degs"); IRasterDataset ras02 = OpenRasterDataset("c:\\data\\test", "negs"); mathFunctionArguments1.Raster = ras01; mathFunctionArguments1.Raster2 = ras02; //Create and initialize 1st function raster dataset with the Raster Function object and its arguments object IFunctionRasterDataset functionRasterDataset1; functionRasterDataset1 = new FunctionRasterDataset(); functionRasterDataset1.Init(rasterFunction1, mathFunctionArguments1); //Create the Raster Function and the Function Arguments object for the 2nd operation IRasterFunction rasterFunction2 = new MathFunction(); IMathFunctionArguments mathFunctionArguments2 = new MathFunctionArguments() as IMathFunctionArguments; //Specify operation to be "Divide" for the 2nd operation mathFunctionArguments2.Operation = esriGeoAnalysisFunctionEnum.esriGeoAnalysisFunctionDivide; //Specify input rasters to the 2nd operation //Use the output function raster dataset from the 1st operation as one of the input mathFunctionArguments2.Raster = functionRasterDataset1; IRasterDataset ras03 = OpenRasterDataset("c:\\data\\test", "cost"); mathFunctionArguments2.Raster2 = ras03; //Create and initialize the 2nd function raster dataset IFunctionRasterDataset functionRasterDataset2; functionRasterDataset2 = new FunctionRasterDataset(); IFunctionRasterDatasetName functionRasterDatasetName = (IFunctionRasterDatasetName)new FunctionRasterDatasetName(); functionRasterDatasetName.FullName = "c:\\output\\math_out.afr"; functionRasterDataset2.FullName = (IName)functionRasterDatasetName; functionRasterDataset2.Init(rasterFunction2, mathFunctionArguments2); //Save the 2nd function raster dataset ITemporaryDataset temporaryDataset = (ITemporaryDataset)functionRasterDataset2; temporaryDataset.MakePermanent(); }
public LineHandler(Trajectory.Node start, Trajectory.Node end, Trajectory.Side side) { this.start = start; this.end = end; this.side = side; float start_x = start.getX()/LineHandler.DIVISOR, end_x = end.getX()/LineHandler.DIVISOR , start_y = 60f - start.getY()/LineHandler.DIVISOR, end_y = 60f - end.getY()/LineHandler.DIVISOR; min_x = Mathf.Min(start_x, end_x); max_x = Mathf.Max(start_x, end_x); min_y = Mathf.Min(start_y, end_y); max_y = Mathf.Max(start_y, end_y); this.function = new MathFunction(new Vector2(start_x,start_y) ,new Vector2(end_x,end_y)); this.scale_function = new MathFunction(new Vector2(start_x,start.getScale()), new Vector2(end_x,end.getScale())); }
private ISurface CreateSegment(int uIdx, int vIdx, MathFunction function) { var meshDensity = Properties.MeshDensity; var uSize = Math.Abs(UDimension.Max - UDimension.Min) /(UDimension.KnotCount - 1); var vSize = Math.Abs(VDimension.Max - VDimension.Min) /(VDimension.KnotCount - 1); var u0 = UDimension.Min + uSize*uIdx; //afv[uIdx][vIdx].X; var u1 = UDimension.Min + uSize*(uIdx + 1); var v0 = VDimension.Min + vSize*vIdx; var v1 = VDimension.Min + vSize*(vIdx + 1); var uKnotsDistance = Math.Abs(u1 - u0); var xCount = Math.Ceiling(uKnotsDistance/meshDensity); var yKnotDistance = Math.Abs(v1 - v0); var yCount = Math.Ceiling(yKnotDistance/meshDensity); var verticesCount = (int) ((++xCount)*(++yCount)); var segmentMeshVertices = new VertexPositionNormalColor[verticesCount]; var k = 0; var x = (float) u0; for (var i = 0; i < xCount; i++, x += meshDensity) { x = x < u1 ? x : (float) u1; var y = (float) v0; for (var j = 0; j < yCount; j++, y += meshDensity) { y = y < v1 ? y : (float) v1; var z = (float) function.SafeCall(x, y); segmentMeshVertices[k++] = new VertexPositionNormalColor(new Vector3(x, y, z), DefaultNormal, DefaultColor); } } return new SimpleSurface(segmentMeshVertices, (int) xCount, (int) yCount); }
private MathFunction FuncStep() { MathFunction fnc; if (_curToken.Value != "Max" && _curToken.Value != "Min") throw new ParseErrorException("Не верное объявление функции, ожидалось Max или Min"); if (_curToken.Value == "Max") fnc = new MathFunction(Target.maximization); else fnc = new MathFunction(Target.minimization); Match(TokenType.Var); if (_curToken.Value != "f") throw new ParseErrorException("Не верное объявление функции, ожидалось f"); Match(TokenType.Var); if (_curToken.Type != TokenType.OpBr) throw new ParseErrorException("Не верное объявление функции, ожидалась открывающая скобка"); Match(TokenType.OpBr); if (_curToken.Type != TokenType.Var) throw new ParseErrorException("Ожидалось объявление переменной"); while (_curToken.Type == TokenType.Var) //читаем все переменные { if (_table.ContainsKey(_curToken.Value)) throw new ParseErrorException("Переменная " + _curToken.Value + " уже объявленна"); _varCount++; _table.Add(_curToken.Value, _varCount); fnc.AddNewVariable(0, _varCount, _curToken.Value); Match(TokenType.Var); if (_curToken.Type == TokenType.Comma) Match(TokenType.Comma); } if (_curToken.Type != TokenType.ClBr) throw new ParseErrorException("Ожидалась закрывающая скобка"); Match(TokenType.ClBr); if (_curToken.Value != "=") throw new ParseErrorException("Ожидалось начало описания функии. Не обнаружен знак '='"); Match(_curToken.Type); while (_curToken.Type != TokenType.SimCol) { if (!(_curToken.Type == TokenType.Sing || _curToken.Type == TokenType.Var || _curToken.Type == TokenType.Number || _curToken.Type == TokenType.OpBr)) throw new ParseErrorException("Не верное описание слагаемого"); int koef = 1; Fraction koefVar = 1; if (_curToken.Type == TokenType.Sing) { if (_curToken.Value == "-") koef = -1; Match(_curToken.Type); } if (_curToken.Type == TokenType.Number || _curToken.Type == TokenType.OpBr) { koefVar = Number(); } if (_curToken.Type != TokenType.Var) throw new ParseErrorException("Ожидалась переменная"); if (!_table.ContainsKey(_curToken.Value)) throw new ParseErrorException("Переменная " + _curToken.Value + " не объявленная"); if (_table[_curToken.Value] == 0) throw new ParseErrorException("Ключевое слово " + _curToken.Value + " не может использоваться, как переменная"); fnc.AddNewVariable(koef * koefVar, _table[_curToken.Value]); Match(_curToken.Type); } Match(_curToken.Type); return fnc; }
/// <summary> /// Applys a rotation effect that oscillates from -mag to +mag and decays over time. /// </summary> /// <param name="camera">The camera the effect is applied to</param> /// <param name="dur">Duration in ms for the effect to occur over</param> /// <param name="decay">Decay coeffecient of the shaking. Use 0 for no decay</param> /// <param name="mag">Maximum magnitude in radians for the camera to rotate</param> /// <param name="freq">Number of times the camera makes a full left -> right -> left pass</param> public CameraShakeEffect(Camera camera, float dur, float decay, float mag, float freq) : base(camera, dur, decay, mag, freq) { magFunction = new DecayFunction(0, 1, decay); oscillateFunction = new OscillatingFunction(0, 1, freq); }
/// <summary> /// Create math function on chart /// </summary> /// <param name="chart">Chart for function</param> /// <param name="func">The math function for display</param> /// <param name="color">Color of function</param> public ChartFunction(Chart chart, MathFunction func, Color color) : base(chart) { Function = func; Color = color; }
/// <summary> /// Create math function on chart /// </summary> /// <param name="chart">Chart for function</param> /// <param name="func">The math function for display</param> public ChartFunction(Chart chart, MathFunction func) : base(chart) { Function = func; Color = Color.Black; }
public Function(object o) { if (o is MathFunction) { mfunc = (MathFunction)o; t = typeof(MathFunction); } else { ofunc = (ObjectFunction)o; t = typeof(ObjectFunction); } }
public void Add(string name, MathFunction func) { Function f = new Function(func); functions.Add(name, f); }
// Runs each of the given delegates on the two numbers via DoMath public static void DoMultipleMath(int x, int y, MathFunction[] functions, MathApplier applier) { foreach (MathFunction function in functions) { applier(x, y, function); } }
public static void DoMath(int x, int y, MathFunction stuff) { System.Console.WriteLine("Result is {0}.", stuff(x, y)); }
public void AddOperator(char name, MathFunction func, int parameters = 2, int precedence = 2, Associative assoc = Associative.LEFT) { Operator op = new Operator(name, func, parameters, precedence, assoc); operators.Add(name, op); }
/// <summary> /// Adds a math function to the evaluation engine. /// </summary> /// <param name="op">Function Name. Case insensitiv</param> /// <param name="func">Function that returns a double and take a List<double> as input</param> public void AddFunction(string op, MathFunction func) { MathFunctions.Add(op.ToLower(), func); }
/// <summary> /// Adds a math operator to the evaluation engine. /// </summary> /// <param name="op">Operator Name. Case insensitiv</param> /// <param name="func">Function that returns a double and take a List<double> as input</param> /// <param name="func">Precedence (2 = +-, 3 = */%, 4 = ^)</param> /// <param name="func">Associative, Left or Right</param> public void AddOperator(char op, MathFunction func, int Parameters = 2, int Precedence = 2, Associative associative = Associative.LEFT) { if (TokenTypes().ContainsKey(op)) { throw new MathOperatorException("Unable to add operators named '(', ')' or ','"); } MathOperators.AddOperator(char.ToLower(op), func, Parameters, Precedence, associative); }