13,824
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <cmath>
#include <ctime>
#include <windows.h>
void sqrt_inv(double x)
{
cout << "x= " << x << endl;
clock_t start = clock();
const float threehalfs = 1.5F;
double xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating VALUE
cout << "i= " << i << endl;
i = 0x5f375a86 - (i >> 1); // gives initial guess y0
x = *(float*)&i; // convert bits BACK to float
cout << "x= " << x << endl;
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
double ans = 1.0 / x;
Sleep(1000);
clock_t finish = clock();
cout << "inv:" << "\t" << ans << "\t" << start << "\t" << finish << "\t" << (finish - start) << endl; // (finish - start) / CLOCKS_PER_SEC
}
int main()
{
double x = 2;
//sqrt_sys(x);
sqrt_inv(x);
//sqrt_Newton(x);
system("pause");
return 0;
}
void sqrt_inv(float x) // 参数类型是float
{
cout << "x= " << x << endl;
clock_t start = clock();
const float threehalfs = 1.5F;
double xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating VALUE
cout << "i= " << i << endl;
i = 0x5f375a86 - (i >> 1); // gives initial guess y0
x = *(float*)&i; // convert bits BACK to float
cout << "x= " << x << endl;
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
double ans = 1.0 / x;
Sleep(1000);
clock_t finish = clock();
cout << "float_inv:" << "\t" << ans << "\t" << start << "\t" << finish << "\t" << (finish - start) << endl; // (finish - start) / CLOCKS_PER_SEC
}
void sqrt_inv(double x) // 类型是double
{
clock_t start = clock();
const double threehalfs = 1.5F;
double xhalf = 0.5f*x;
long long i = *(long long*)&x; // get bits for floating VALUE
cout << "i= " << i << endl;
i = 0x5fe6ec85e7de30da - (i >> 1); // gives initial guess y0
x = *(double*)&i; // convert bits BACK to float
cout << "x= " << x << endl;
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(threehalfs - xhalf*x*x); // Newton step, repeating increases accuracy
double ans = 1.0 / x;
Sleep(1000);
clock_t finish = clock();
cout << "double_inv:" << "\t" << ans << "\t" << start << "\t" << finish << "\t" << (finish - start) << endl; // (finish - start) / CLOCKS_PER_SEC
}