Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other examples of magical calculations

I have seen this topic here about John Carmack's magical way to calculate square root, which refers to this article: http://www.codemaestro.com/reviews/9. This surprised me a lot, I just didn't ever realized that calculating sqrt could be so faster.

I was just wondering what other examples of "magic" exist out there that computer games use to run faster.

UPDATE: John Carmack is not the author of the magic code. This article tells more. Thanks @moocha.

like image 948
Paulo Guedes Avatar asked Dec 01 '08 13:12

Paulo Guedes


Video Answer


2 Answers

There is a book which gathers many of those 'magic tricks' and that may be interesting for you: The Hacker's Delight.

You have for example many tricks like bit twiddling hacks etc... (you have several square root algorithms for example that you can see on the google books version)

like image 169
Piotr Lesnicki Avatar answered Oct 14 '22 22:10

Piotr Lesnicki


Not exactly a mathematical hack, but I like this one about Roman Numerals in Java6:

public class Example {
    public static void main(String[] args) {
        System.out.println(
            MCMLXXVII + XXIV
        );
    }
}

will give you the expected result (1977 + 24 = 2001), because of a rewrite rule:
class Transform extends TreeTranslator, an internal class of the Java compiler.

Transform visits all statements in the source code, and replaces each variable whose name matches a Roman numeral with an int literal of the same numeric value.

public class Transform extends TreeTranslator {
    @Override
    public void visitIdent(JCIdent tree) {
        String name = tree.getName().toString();
        if (isRoman(name)) {
            result = make.Literal(numberize(name));
            result.pos = tree.pos;
        } else {
            super.visitIdent(tree);
        }
    }
}
like image 30
VonC Avatar answered Oct 14 '22 23:10

VonC