-
平方根计算
编辑
功 能: 一个非负实数的
平方根
函数原型: 在VC6.0中的
math.h头文件的函数原型为double sqrt(double);
说明:sqrt系Square Root Calculations(平方根计算),通过这种运算可以考验
CPU的浮点能力。
-
中文名
- 平方根函数 外文名
- sqrt 功 能
- 计算一个非负实数的平方根
-
函数原型
- double sqrt(double) 应 用
- 考验CPU的浮点能力 头文件
- math.h 本 质
- 程序函数
程序例
编辑
1
2
3
4
5
6
7
8
9
|
#include<math.h>
#include<stdio.h>
int
main(
void
)
{
double
x = 4.0,result;
result =
sqrt
(x);
//result*result=x
printf
(
"Thesquarerootof%fis%f\n"
,x,result);
return
0;
}
|
VC 2008后为
重载函数,原型为 float sqrt (float),double sqrt (double),double long sqrt(double long)
注意没有sqrt (int),但是返回值可以为int
John Carmack's sqrt [C/C++]
Carmack的sqrt计算函数在批量计量时的耗时比系统库函数还要少,优异的性能的根本原因就是那个令无数人膜拜的魔数0x5F3759DF。
1
2
3
4
5
6
7
8
9
10
11
12
|
static
float
CarmackSqrt (
float
x)
{
float
xhalf = 0.5f * x;
int
i = *(
int
*)&x;
// get bits for floating VALUE
i = 0x5f3759df - (i>>1);
// gives initial guess y0
x = *(
float
*)&i;
// convert bits BACK to float
x = x*(1.5f - xhalf*x*x);
// Newton step, repeating increases accuracy
x = x*(1.5f - xhalf*x*x);
// Newton step, repeating increases accuracy
x = x*(1.5f - xhalf*x*x);
// Newton step, repeating increases accuracy
return
(1 / x);
}
|
pascal
编辑
a := sqrt(sqr(x-x[j])+sqr(y-y[j]));
b := sqrt(sqr(x-x[k])+sqr(y-y[k]));
c := sqrt(sqr(x[j]-x[k])+sqr(y[j]-y[k]));
gcc
编辑
例如:
1
2
3
4
5
6
7
8
9
10
11
12
|
/*文件名test.c*/
#include<stdio.h>
#include<math.h>
//#include<stdlib.h>
void
main()
{
double
x;
double
n=
rand
()%100;
printf
(
"%lf\n"
,n);
x=
sqrt
(n);
printf
(
"%lf\n"
,x);
}
|
EXCEL函数
编辑Python函数
编辑
#!/usr/bin/env python
import math # This will import math module
print("math.sqrt(100) is:", math.sqrt(100))
C++
编辑
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#include <iostream>
//这里的cmath等价于C的math.h
#include <cmath>
using
namespace
std;
int
main()
{
double
x, result;
cin>>x;
result=
sqrt
(x);
cout<<x<<
"的平方根是"
<<result<<endl;
return
0;
}
//cmath等价于math.h,其就是using math.h的函数
//VC 2008后为重载函数,原型为 float sqrt (float),double sqrt (double),double long sqrt(double long)
//注意没有sqrt (int),但是返回值可以为int
|