给定一个整数N和一个公差等级L ,任务是使用牛顿方法找到该数字的平方根。
例子:
Input: N = 16, L = 0.0001
Output: 4
42 = 16
Input: N = 327, L = 0.00001
Output: 18.0831
牛顿法:
假设N为任意数字,则N的平方根可以由以下公式给出:
root = 0.5 * (X + (N / X)) where X is any guess which can be assumed to be N or 1.
- 在上式中,X是N的任何假定平方根和根是N的正确的平方根。
- 公差极限是X和允许的根之间的最大差值。
方法:可以按照以下步骤计算答案:
- 将X分配给N本身。
- 现在,开始循环并继续计算根,该根肯定会移向N的正确平方根。
- 检查假定的X与计算的根之间的差异,如果尚未在公差范围内,则更新根并继续。
- 如果计算出的根在允许的公差内,则跳出循环。
- 打印根目录。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the square root of
// a number using Newtons method
double squareRoot(double n, float l)
{
// Assuming the sqrt of n as n only
double x = n;
// The closed guess will be stored in the root
double root;
// To count the number of iterations
int count = 0;
while (1) {
count++;
// Calculate more closed x
root = 0.5 * (x + (n / x));
// Check for closeness
if (abs(root - x) < l)
break;
// Update root
x = root;
}
return root;
}
// Driver code
int main()
{
double n = 327;
float l = 0.00001;
cout << squareRoot(n, l);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the square root of
// a number using Newtons method
static double squareRoot(double n, double l)
{
// Assuming the sqrt of n as n only
double x = n;
// The closed guess will be stored in the root
double root;
// To count the number of iterations
int count = 0;
while (true)
{
count++;
// Calculate more closed x
root = 0.5 * (x + (n / x));
// Check for closeness
if (Math.abs(root - x) < l)
break;
// Update root
x = root;
}
return root;
}
// Driver code
public static void main (String[] args)
{
double n = 327;
double l = 0.00001;
System.out.println(squareRoot(n, l));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to return the square root of
# a number using Newtons method
def squareRoot(n, l) :
# Assuming the sqrt of n as n only
x = n
# To count the number of iterations
count = 0
while (1) :
count += 1
# Calculate more closed x
root = 0.5 * (x + (n / x))
# Check for closeness
if (abs(root - x) < l) :
break
# Update root
x = root
return root
# Driver code
if __name__ == "__main__" :
n = 327
l = 0.00001
print(squareRoot(n, l))
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the square root of
// a number using Newtons method
static double squareRoot(double n, double l)
{
// Assuming the sqrt of n as n only
double x = n;
// The closed guess will be stored in the root
double root;
// To count the number of iterations
int count = 0;
while (true)
{
count++;
// Calculate more closed x
root = 0.5 * (x + (n / x));
// Check for closeness
if (Math.Abs(root - x) < l)
break;
// Update root
x = root;
}
return root;
}
// Driver code
public static void Main()
{
double n = 327;
double l = 0.00001;
Console.WriteLine(squareRoot(n, l));
}
}
// This code is contributed by AnkitRai01
输出:
18.0831