Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using MathConsoleApplication;
- using org.mariuszgromada.math.mxparser;
- using System.Diagnostics;
- public class Bisection
- {
- private static float EPSILON = (float)0.01;
- private static double func(string expression, double x)
- {
- expression = SobstitutionClass.replaceX(expression, x);
- Expression e = new Expression(expression);
- double res = e.calculate();
- //Console.WriteLine(e.getErrorMessage().ToString());
- return res;
- }
- public static void bisection(string expression,
- double a,
- double b)
- {
- if (a*b >= 0)
- {
- Console.WriteLine("a e b non sono corretti");
- return;
- }
- double c = a;
- Stopwatch stopWatch = new Stopwatch();
- stopWatch.Start();
- while ((b - a) >= 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)
- {
- // 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;
- }
- stopWatch.Stop();
- TimeSpan ts = stopWatch.Elapsed;
- string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
- ts.Hours, ts.Minutes, ts.Seconds,
- ts.Milliseconds / 10);
- Console.WriteLine($"la radice equivale a {Math.Round(c, 15)} in {elapsedTime}");
- }
- }
- using System.Globalization;
- namespace MathConsoleApplication
- {
- public class SobstitutionClass
- {
- public static string replaceX(string expression, double x)
- {
- NumberFormatInfo nfi = new NumberFormatInfo();
- nfi.NumberDecimalSeparator = ".";
- 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);
- expression = expression.Insert(i, $"({x.ToString(nfi)})");
- }
- else
- {
- string tmpRepace = $"*{x.ToString(nfi)}";
- expression = expression.Remove(i, "x".Length);
- expression = expression.Insert(i, tmpRepace);
- }
- }
- else
- {
- expression = expression.Remove(i, "x".Length).Insert(i, x.ToString());
- }
- {
- }
- }
- }
- return expression;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement