Carmack's inverse square root (I .e. 1/SQRT (x) Function

Source: Internet
Author: User
Tags float number

In quakeiiiSource codeThere is a function for finding inverse square root (that is, 1/SQRT (x,
Implemented by CarmackAlgorithmSome CPUs are 4 times faster than normal (float) (1.0/SQRT (x! (SQRT (x) in the above expression is still calculated by directly calling the fsqrt command !!!)

Carmack'sCodeAs follows:

Float q_rsqrt (float number)
{
Long I;
Float X2, Y;
Const float threehalfs = 1.5f;

X2 = Number * 0.5f;
Y = number;
I = * (long *) & Y; // edevil floating point bit level hacking
I = 0x5f3759df-(I> 1); // What is the fuck?
Y = * (float *) & I;
Y = y * (threehalfs-(X2 * y); // 1st Iteration
// Y = y * (threehalfs-(X2 * y); // 2nd iteration, this can be removed

# Ifndef q3_vm
# Ifdef _ Linux __
Assert (! Isnan (y); // bk010122-FPE?
# Endif
# Endif
Return y;
}

It is actually an iteration of the Newton method, but Carmack uses a mysterious constant, 0x5f3759df. The result is obtained after only one iteration.

Chris lomont from Purdue University wrote a paper titled paper.

Genius is a genius, but Carmack is a high school graduate.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.