math.sqrt vs. Newton-Raphson在c#中查找根的方法

Ale*_*lex 3 .net c#

我正在做一个需要这个的家庭作业项目:

下面你将找到我用于使用Newton-Raphson方法计算数字平方根的代码.将其包含在您的项目中.对于这个项目,你的工作就是编写一个测试工具来测试我编写的代码.仔细阅读方法序言,了解该功能应如何工作.您的测试工具将提供以下循环:

  1. 提示用户输入测试值.
  2. 获取用户的输入.如果输入零,程序将打印出报告并终止.
  3. 调用此项目中提供的Sqrt方法,并将返回值保存在double变量中.
  4. 调用Math类中内置的Sqrt方法,并将返回值保存在第二个double变量中.
  5. 比较这两个值,看它们是否相等.
  6. 当用户指示它们已完成时(通过输入零)显示一个显示此信息的报告:*您执行了多少个测试用例*传递了多少*多少次失败

所以我在大约15分钟内完成了所有这些,没有任何问题,但是为了额外的功劳,他要求我们找到他的Sqrt方法有什么问题并修复它,使其返回值等于.net框架的Math.Sqrt返回值.我似乎无法在他的方法中找到问题,我想找到它,所以我想知道是否有人能指出我正确的方向,他的Sqrt方法有什么问题?谢谢.

这是我的完整代码:

// declare variables
    double userInput = 0.0;
    double debrySqrtReturnValue = 0.0;
    double dotNetSqrtReturnValue = 0.0;
    int testCasesExecuted = 0;
    int testsPassed = 0;
    int testsFailed = 0;
    bool isEqual = false;

    do
    {
        // Prompt the user to enter in a test value
        Console.Write("Please enter a positive integer value: ");
        userInput = double.Parse(Console.ReadLine());

        if (userInput != 0)
        {
            debrySqrtReturnValue = Sqrt(userInput);
            dotNetSqrtReturnValue = Math.Sqrt(userInput);

            Console.WriteLine("The square root of {0} is: {1}", userInput, debrySqrtReturnValue);
            Console.WriteLine("The real square root of {0} is: {1}\n", userInput, dotNetSqrtReturnValue);

            if (debrySqrtReturnValue == dotNetSqrtReturnValue)
                isEqual = true;
            else
                isEqual = false;

            if (isEqual)
                testsPassed++;
            else
                testsFailed++;

            testCasesExecuted++;
        }
    } while (userInput != 0);

    Console.WriteLine("\n\n--------------------------------Report---------------------------------");
    Console.WriteLine("test cases excecuted: {0}", testCasesExecuted);
    Console.WriteLine("tests passed: {0}", testsPassed);
    Console.WriteLine("tests failed: {0}", testsFailed); 

    Console.ReadLine();
}


// The Sqrt method
// Purpose: to compute the square root of a number
// Parameters: a positive, non-zero integer
// returns: a double, which is the square root of the number
// ---------------------------------------------------------
static double Sqrt(double number)
{
    // constants to use in the calculation
    const int FIRST_APPROX = 2;
    const double EPS = 0.001;

    // a local variable
    double xN = 0;

    // pick 2 as first approximation
    double xNPlus1 = FIRST_APPROX;
    do
    {
        xN = xNPlus1; 
        xNPlus1 = xN - ((xN * xN - number) / (FIRST_APPROX * xN));

    } while (Math.Abs(xNPlus1 - xN) > EPS);
    return xN;
}
Run Code Online (Sandbox Code Playgroud)

}

Roo*_*oke 5

尝试设置const double EPS = 0.000000001;- 那是你的epsilon.这就决定了答案的精确度.