If you want to support more it can be easily modified.
FormulaParser.cs
private static double ApplyFunction(string name, double[] args)
{
if (args.Length == 0)
throw new ArgumentException($"No arguments provided for function: {name}");
switch (name)
{
case "pow":
if (args.Length != 2) throw new ArgumentException("pow requires 2 arguments");
return Math.Pow(args[0], args[1]);
case "abs":
return Math.Abs(args[0]);
case "sqrt":
return Math.Sqrt(args[0]);
case "sin":
return Math.Sin(args[0] * Math.PI / 180);
case "cos":
return Math.Cos(args[0] * Math.PI / 180);
case "random":
if (args.Length != 2) throw new ArgumentException("random requires 2 arguments");
return RandomInstance.Next((int)args[0], (int)args[1] + 1);
case "min":
if (args.Length != 2) throw new ArgumentException("min requires 2 arguments");
return Math.Min(args[0], args[1]);
case "max":
if (args.Length != 2) throw new ArgumentException("max requires 2 arguments");
return Math.Max(args[0], args[1]);
case "dice":
if (args.Length != 2) throw new ArgumentException("dice requires 2 arguments");
return Enumerable.Range(0, (int)args[0]).Sum(_ => RandomInstance.Next(1, (int)args[1] + 1));
case "chance":
return RandomInstance.NextDouble() * 100 < args[0] ? 1.0 : 0.0;
default:
throw new ArgumentException($"Unknown function: {name}");
}
}
private static double ApplyOperator(double a, double b, string op)
{
switch (op)
{
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
if (b == 0) throw new DivideByZeroException();
return a / b;
case "%":
if (b == 0) throw new DivideByZeroException();
return a % b;
default:
throw new ArgumentException($"Unknown operator: {op}");
}
}