C++ 中快速平方的倒數
在這個問題中,我們給定了一個整數 x。我們的任務是計算一個 32 位浮點數的快速平方倒數。
尋找數字的平方倒數的演算法在程式設計中非常有用,例如影片遊戲中進行向量歸一化、3D 圖形中等等。
演算法:
步驟 1: 該演算法將浮點值轉換為整數。
步驟 2: 對整數值進行操作,返回平方倒數的近似值。
步驟 3: 使用步驟 1 中使用的方法將整數值轉換回浮點數。
步驟 4: 進行近似操作以提高精度,方法是使用牛頓法。
為說明演算法的工作原理而編寫的程式:
示例
#include<iostream>
using namespace std;
float calcInvSqRoot( float n ) {
const float threehalfs = 1.5F;
float y = n;
long i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( (n * 0.5F) * y * y ) );
return y;
}
int main(){
int n = 256;
float invSqRoot = calcInvSqRoot(n);
cout<<"The inverse square root of the number "<<n<<" is "<<invSqRoot;
return 0;
}輸出 −
The inverse square root of the number 256 is 0.0623942
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP