二分法 - C#

时间:2017-10-09 21:27:31

标签: c# .net algorithm math bisection

我有一个名为 Bisection method 的函数,它接受函数的<4>参数委托开始和区间的结束和解决方案的用户猜测以下是功能:

  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;
        }

        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;
            else
            {
                if (fun(start) == 0)
                    return start;
                else return end;
            }

            avg = (start + end) / 2;
        }
        while ( tolerance > 0.0001 );

        return end;
    }

现在我想处理一些案例:

1 - 我们可以输入一个负数的开头吗?如果是这样,我们如何处理sqrt?

2 - 如果用户从零开始输入间隔,并且传递给委托的函数In有Ln()或Log(),我们该如何处理?< / p>

1 个答案:

答案 0 :(得分:2)

问题是:如果funMath.Sqrt(double)start为否定,那么fun(start)NaNfun(start) * fun(end)NaN > 0,但是false评估为NaN

您需要明确检查double fstart = fun(start); double fend = fun(end); if ( double.IsNaN(fstart) || double.IsNaN(fend) || fstart * fend > 0 ) { Console.WriteLine("wrong Entry"); return -1; // this may not be the best way to report an error }

double.IsNaN(fun(avg))

此外,您可能需要检查循环内的fun = x => x * Math.Sqrt(x*x-1)以处理例如start < -1 end > 1private async void LoginWithGoogle_Clicked(object sender, EventArgs e) { ShowLoader(true); var authRequest = "https://accounts.google.com/o/oauth2/v2/auth" + "?response_type=code" + "&scope=email%20profile" + "&redirect_uri=" + Constants.GoogleRedirectUri + "&client_id=" + Constants.GoogleClientId; var webView = new WebView { Source = authRequest, HeightRequest = 1 }; webView.Navigated += WebViewOnNavigatedForGoogle; Content = webView; ShowLoader(false); }

。{/ 1}