Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using MathConsoleApplication;
- using org.mariuszgromada.math.mxparser;
- public class Bisection
- {
- private static float EPSILON = (float)0.01;
- // An example function whose
- // solution is determined using
- // Bisection Method. The function
- // is x^3 - x^2 + 2
- private static double func(string expression, double x)
- {
- expression = SobstitutionClass.replaceX(expression, x);
- Expression e = new Expression(expression);
- return e.calculate();
- }
- public static void bisection(string expression,
- double a,
- double b)
- {
- if (func(expression, a) * func(expression, b) >= 0)
- {
- Console.WriteLine("a e b non sono corretti");
- return;
- }
- double c = a;
- while ((b - a) >= EPSILON)
- {
- // Find middle point
- c = (a + b) / 2;
- // Check if middle
- // point is root
- if (func(expression, c) == 0.0)
- break;
- // Decide the side
- // to repeat the steps
- else if (func(expression, c) * func(expression, a) < 0)
- b = c;
- else
- a = c;
- }
- Console.WriteLine($"la radice equivale a {Math.Round(c, 15)}");
- }
- }
- namespace MathConsoleApplication
- {
- public class SobstitutionClass
- {
- public static string replaceX(string expression, double x)
- {
- for (int i = 0; i < expression.Length; i++)
- {
- if (expression[i] == 'x')
- {
- if (i - 1 >= 0)
- {
- if (expression[i - 1] == '(' || expression[i - 1] == '+' || expression[i - 1] == '-' || expression[i - 1] == '*' || expression[i - 1] == '/')
- {
- expression = expression.Remove(i, "x".Length - 1);
- expression = expression.Insert(i, x.ToString());
- }
- else
- {
- string tmpRepace = $"*{x.ToString()}";
- expression = expression.Remove(i, "x".Length);
- expression = expression.Insert(i, tmpRepace);
- }
- }
- else
- {
- expression = expression.Remove(i, "x".Length - 1).Insert(i, x.ToString());
- }
- {
- }
- }
- }
- return expression;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement