# CoffeeScript 平方根倒数快速算法

2022-06-29 17:00 更新

## 解决方案

``````###

Author: Jason Giedymin <jasong _a_t_ apache -dot- org>
http://www.jasongiedymin.com
https://github.com/JasonGiedymin

###

approx_const_quake_32 = 0x5f3759df # See [1]
approx_const_32 = 0x5f375a86 # See [2]
approx_const_64 = 0x5fe6eb50c7aa19f9 # See [2]

fastInvSqrt_typed = (n, precision=1) ->
# 使用类型数组。现在只能在浏览器中操作。
# Node.JS 的版本即将推出。

y = new Float32Array(1)
i = new Int32Array(y.buffer)

y[0] = n
i[0] = 0x5f375a86 - (i[0] >> 1)

for iter in [1...precision]
y[0] = y[0] * (1.5 - ((n * 0.5) * y[0] * y[0]))

return y[0]

### 单次运行示例

testSingle = () ->
example_n = 10

console.log("Fast InvSqrt of 10, precision 1: #{fastInvSqrt_typed(example_n)}")
console.log("Fast InvSqrt of 10, precision 5: #{fastInvSqrt_typed(example_n, 5)}")
console.log("Fast InvSqrt of 10, precision 10: #{fastInvSqrt_typed(example_n, 10)}")
console.log("Fast InvSqrt of 10, precision 20: #{fastInvSqrt_typed(example_n, 20)}")
console.log("Classic of 10: #{1.0 / Math.sqrt(example_n)}")

testSingle()``````

App下载