I have a simple bisection method solver that I was told it has some problems in design and I need my code to be reviewed, so I was hoping for someone to give me guideline on how to improve my code.
It starts with a delegate:
public delegate double MyFun (double x) ;
A class to add functions:
class functions
{
public static double fun1(double x) => Math.Pow(x,2) - 3;
public static double fun2(double x) => 5* Math.Pow(x, 3) - 2* Math.Pow(x, 2) + 3 * x - 2;
public static double fun3(double x) => 2 * Math.Sqrt(x) ;
}
A class that has a function that solves the equation. It has a function that takes 4 input parameters: delegate, start point, end point, guess of solution.
class Bisection
{
public static double Bisection_method (MyFun fun , double start , double end , double? guess)
{
if ( fun(start) * fun(end) > 0 )
{
Console.WriteLine("wrong Entry");
return -1;
}
if (fun(start) == 0)
{
return start;
}
double avg,tolerance,sign;
avg = (guess.HasValue) ? guess.Value : ( (start + end) / 2 );
do
{
tolerance = Math.Abs ( fun(end) - fun(start) );
sign = fun(start) * fun(avg);
if (sign < 0)
end = avg;
else if (sign > 0)
start = avg;
avg = (start + end) / 2;
}
while ( tolerance > 0.0001 );
return end;
}
}
Then the main method:
class Program
{
static void Main(string[] args)
{
MyFun fun1 = functions.fun1;
double start = 0;
double end = 500;
double guess = 10;
double answer = Bisection.Bisection_method(fun1, start, end, guess);
Console.WriteLine($"The Root = {answer}");
}
}
I was hoping for someone to help me how to improve this simple code design and there is also some cases that I need to handle.
fun3do? Pretty hard to answer that... \$\endgroup\$