Fast Inverse Square Root

I expect no replies to this thread - because there are no
answers, but I want to raise awareness of a faculty of other
languages that is missing in Flash that would really help 3D and
games to be built in Flash.
Below is an optimisation of the Quake 3 inverse square root
hack. What does it do? Well in games and 3D we use a lot of vector
math and that involves calculating normals. To calculate a normal
you divide a vector's parameters by it's length, the length you
obtain by pythagoras theorem. But of course division is slow - if
only there was a way we could get 1.0/Math.sqrt so we could just
multiply the vector and speed it up.
Which is what the code below does in Java / Processing. It
runs at the same speed as Math.sqrt, but for not having to divide,
that's still a massive speed increase.
But we can't do this in Flash because there isn't a way to
convert a Number/float into its integer-bits representation. Please
could everyone whinge at Adobe about this and give us access to a
very powerful tool. Even the guys working on Papervision are having
trouble with this issue.

that's just an implementation of newton's method for finding
the zeros of a differentiable function. for a given x whose inverse
sq rt you want to find, the function is:
f(y) = 1/(y*y) - x;
1. you can find the positive zero of f using newton's method.
2. you only need to consider values of x between 1 and 10
because you can rewrite x = 10^^E * m, where 1<=m<10.
3. the inverseRt(x) = 10^^(-E/2) * inverseRt(m)
4. you don't have to divide E by 2. you can use bitwise shift
to the right by 1.
5. you don't have to multiply 10^^(-E/2) by inverseRt(m): you
can use a decimal shift of inverseRt(m);
6. your left to find the positive zero of f(y) = 1/(y*y) - m,
1<=m<10.
and at this point i realized what, i believe, is a much
faster way to find inverse roots: use a look-up table.
you only need a table of inverse roots for numbers m,
1<m<=10.
for a given x = 10^^E*m = 10^^(e/2) *10^^(E-e/2)*m, where e
is the largest even integer less than or equal to E (if E is
positive, e is the greatest even integer less than or equal to E,
if E is negative), you need to look-up, at most, two inverse roots,
perform one multiplication and one decimal shift:
inverseRt(x) = 10^^(-e) * inverseRt(10) *inverseRt(m), if
E-e/2 = 1 and
inverseRt(x) = 10^^(-e) * inverseRt(m), if E-e/2 = 0.

Similar Messages

  • Fastest square root algorithm

    I was looking for a fast algorythm for integer square roots and I found this one http://medialab.freaknet.org/martin/src/sqrt/.
    The algorithm comes from a book by Mr C. Woo on how to do maths on an abacus.
    I post the javaized version here in case anyone finds it interesting.
    I believe this is the fastest square root function in existance for integers (and in game programming much of the time you aren't interested in fractions)
    /* Fast interger square root adapted from algorithm by Martin Guy @ UKC, June 1985.
        *   Origonally from a book on programming abaci by Mr C. Woo.
       public static int fastSqrt2(int n)
          int op, res, one;
          op = n;
          res = 0;
          /* "one" starts at the highest power of four <= than the argument. */
          one = 1 << 30;   /* second-to-top bit set */
          while (one > op) one >>= 2;
          while (one != 0)
             if (op >= res + one)
                op = op - (res + one);
                res = res +  (one<<1);
             res >>= 1;
             one >>= 2;
          return(res);
       }

    public static double sqrt(double a){
      if(a<0) throw new IllegalArgumentException("number<0");
      double precision=0.001;
      double x_nMinus1 = -1;
      double x_n = 1;
      while( Math.abs(x_n - x_nMinus1) > precision ) {
        x_nMinus1 = x_n;
        x_n = (x_nMinus1 * x_nMinus1 + a) / (2*x_nMinus1);          
      return x_n;           
    }

  • Fast square root algorithm

    Does anyone here know where I can find an algorithm for a faster square root method than the one provided in java.lang.Math? I've tried Google, but can't come up with anything useful...
    Thanks in advance!

    Well, these guys writing JVM's are getting they wages
    for something.
    Also, how would Java compete to C/C++ on
    computational tasks without this?So you're only guessing. You assume that the JVM has a SQRT instruction. I checked but I couldn't find any. The other possibility is that the Math library is implemented using JNI. Well it may be in some standard libraries but there's no guarantee and also remember that a JNI call carries a lot of overhead so I'm not that sure it would pay off.
    If you can guess I'm entiteled to a guess too -:) I would be very surprised if Java generally would support a hardware accelerated square root calculation. On the other hand a C++ compiler wouldn't automatically do it either.

  • How to take square root of it

    Hi Folks!
    Can anybody tell me how to take square root of this value "bi"?
    BigInteger bi = BigInteger.valueOf(2000000000);
    Thanks in advance.

    I wrote this simple sqrt function for BigInteger.
    * Returns the largest BigInteger, n, such that bigInt>=n*n.
    * If round is true, the function returns n+1 if it is closer to actual square root.
    * @param round if true, attempt to find a closer value by rounding up.
    * @return <tt>round ? round(sqrt(bigInt)) : floor(sqrt(bigInt))</tt>
    public static BigInteger sqrt(BigInteger bigInt, boolean round){
         BigInteger op = bigInt;
         BigInteger res = BigInteger.ZERO;
         BigInteger tmp;
         int shift = bigInt.bitLength()-1;     
         shift -= shift&1;
         // set one to highest power of 4 <= bigInt
         BigInteger one = BigInteger.ONE.shiftLeft(shift);
         while(one.signum()>0){
              tmp = res.add(one);
              if(op.compareTo(tmp)>=0){
                   op = op.subtract(tmp);
                   res = res.add(one.shiftLeft(1));
              res = res.shiftRight(1);
              one = one.shiftRight(2);
         if(round&&op.signum()!=0){
              op = bigInt.subtract(res.pow(2));
              if(op.compareTo(res)>0){
                   res = res.add(BigInteger.ONE);
         return res;
    }

  • How to print square root ?

    Hi...i want to print square root on command prompt and a symbol(i don't know what it's name for second symbol). But i get a problem. Below is my code. For what i understand i should use \u221A right? :-
    public class Test
         public static void main(String[]args)
              try
                   System.out.println("\u221A");
                   System.out.println("\u00ea");
              catch(Exception e)
                   e.printStackTrace();
    }But the result is only question mark...can someone show me the right way and what's wrong to my code. I very appreciate to any help. Thank you.

    but it does show up in swing components
    import javax.swing.*;
    import java.awt.*;
    public class printsymb
         private static final String SYMBOL = String.valueOf( '\u221A' );
         public static void main( String args[] )
              display( SYMBOL );
              System.out.print( SYMBOL );
              System.out.println( 4 );
         private static void display( String symbol )
              JTextArea text = new JTextArea( symbol );
              JFrame f = new JFrame();
              f.add( text, BorderLayout.CENTER );
              enableJFrame( f );
         private static void enableJFrame( JFrame frame )
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setSize( 320, 240 );
              frame.setVisible( true );
    }you can always put it out like this "sqrt(someExp)" can't you?
    Edited by: scphan on Apr 4, 2009 1:41 PM

  • How to find square root, log recursively???

    I need to find the square root of a number entered recursively and log as well. Your help would be greatly appreciated. Thanks in advance!
    import java.io.*;
    /**Class provides recursive versions
    * of simple arithmetic operations.
    public class Ops2
         private static BufferedReader in = null;
         /**successor, return n + 1*/
         public static int suc(int n)
              return n + 1;
         /**predecessor, return n - 1*/
         public static int pre(int n)
              if (n == 0)
                   return 0;
              else
                   return n - 1;
         /**add two numbers entered*/
         public static int add(int n, int m)
              if (m == 0)
                   return n;
              else
                   return suc(add(n, pre(m)));
         /**subtract two numbers entered*/
         public static int sub(int n, int m)
              if (n < m)
                   return 0;
              else if (m == 0)
                   return n;
              else
                   return pre(sub(n, pre(m)));
         /**multiply two numbers entered*/
         public static int mult(int n, int m)
              if (m == 0)
                   return 0;
              else
                   return add(mult(n, pre(m)), n);
         /**divide two numbers entered*/
         public static int div(int n, int m)
              if (n < m)
                   return 0;
              else
                   return suc(div(sub(n, m), m));
         /**raise first number to second number*/
         public static int exp(int n, int m)
              if (m == 0)
                   return 1;
              else
                   return mult(exp(n, pre(m)), n);
         /**log of number entered*/
         public static int log(int n)
              if (n < 2)
                   return 0;
              else
                   return suc(log(div(n, 2)));
         /**square root of number entered*/
         public static int sqrt(int n)
              if (n == 0)
                   return 0;
              else
                   return sqrt(div(n, ));
         /**remainder of first number entered divided by second number*/
         public static int mod(int n, int m)
              if (n < m)
                   return 0;
              else
                   return mod(div(n, pre(m)), m);
         public static void prt(String s)
              System.out.print(s);
         public static void prtln(String s)
              System.out.println(s);
         public static void main(String [ ] args)
              prtln("Welcome to the amazing calculator");
              prtln("It can add, multiply and do powers for");
              prtln("naturals (including 0). Note that all the");
              prtln("HARDWARE does is add 1 or substract 1 to any number!!");
              in = new BufferedReader(new InputStreamReader ( System.in ) );
              int It;
              while ( (It = getOp()) >= 0)
                   prt("" + It + "\n");
            private static int getOp( )
            int first, second;
            String op;
            try
                System.out.println( "Enter operation:" );
                do
                    op = in.readLine( );
                } while( op.length( ) == 0 );
             System.out.println( "Enter first number: " );
                first = Integer.parseInt( in.readLine( ) );
                System.out.println( "Enter second number: " );
                second = Integer.parseInt( in.readLine( ) );
             prtln("");
             prt(first + " " + op + " " + second + " = ");
                switch( op.charAt( 0 ) )
                  case '+':
                    return add(first, second);
                  case '-':
                       return sub(first, second);
                  case '*':
                    return mult(first, second);
                  case '/':
                       return div(first, second);
                  case '^':
                    return exp(first, second);
                  case 'v':
                       return log(first);
                  case 'q':
                       return sqrt(first);
                  case '%':
                       return mod(first, second);
                  case 's':
                       return suc(first);
                  case 'p':
                       return pre(first);
                  default:
                    System.err.println( "Need +, *, or ^" );
                    return -1;
            catch( IOException e )
                System.err.println( e );
                return  0;
    }

    Hi,
    Is there any one to make a program for me in Turbo
    C++ for Dos, which can calculate the square root of
    any number without using the sqrt( ) or any ready
    made functions.
    The program should calculate the s.root of the number
    by a formula or procedure defined by the user
    (programmer).
    Thanks.This is a Java forum!
    If you want Java help:
    1. Start your own thread.
    2. Use code tags (above posting box) if you post code.
    3. No one will write the program for you. We will help by answering your questions and giving advice on how to fix problems in code you wrote.
    4. The formula you need to implement is given above by dizzy.

  • Problems with square root approximations with loops program

    i'm having some trouble with this program, this loop stuff is confusing me and i know i'm not doing this correctly at all. the expected values in the tester are not matching up with the output. i have tried many variations of the loop in this code even modifying the i parameter in the loop which i guess is considered bad form. nothing seems to work...
    here is what i have for my solution class:
    /** A class that takes the inputted number by the tester and squares it, and
    *  loops guesses when the nextGuess() method is called. The epsilon value is
    *  also inputted by the user, and when the most recent guess returns a value
    *  <= epsilon, then the hasMoreGuesses() method should return false.
    public class RootApproximator
       /** Takes the inputted values from the tester to construct a RootApproximator.
        * @param val the value of the number to be squared and guessed.
        * @param eps the gap in which the approximation is considered acceptable.
         public RootApproximator(double val, double eps)
              value = val;
              square = Math.sqrt(val);
              epsilon = eps;
       /** Uses the algorithm where 1 is the first initial guess of the
        *  square root of the inputted value. The algorithm is defined by
        *  "If X is a guess for a square root of a number, then the average
        *  of X and value/X is a closer approximation.
        *  @return increasingly closer guesses as the method is continually used.
       public double nextGuess()
             final int TRIES = 10000;
             double guess = 1;
              for (double i = 1; i < TRIES; i++)
                   double temp = value / guess;
                   guess = (guess + temp) / 2.0;
              return guess;
       /** Determines if there are more guesses left if the difference
        *  of the square and current guess are not equal to or less than
        *  epsilon.
        *  @return the value of the condition.
       public boolean hasMoreGuesses()
              return (square - guess <= epsilon);
       private double square;
       private double value;
       private double epsilon;
       private double guess;
    here is the tester:
    public class RootApproximatorTester
       public static void main(String[] args)
          double a = 100;
          double epsilon = 1;
          RootApproximator approx = new RootApproximator(a, epsilon);
          System.out.println(approx.nextGuess());
          System.out.println("Expected: 1");
          System.out.println(approx.nextGuess());
          System.out.println("Expected: 50.5");
          while (approx.hasMoreGuesses())
             approx.nextGuess();
          System.out.println(Math.abs(approx.nextGuess() - 10) < epsilon);
          System.out.println("Expected: true");
    and here is the output:
    10.0
    Expected: 1 // not sure why this should be 1, perhaps because it is the first guess.
    10.0
    Expected: 50.5 // (100 + 1) / 2, average of the inputted value and the first guess.
    true
    Expected: true
    i'm new to java this is my first java course and this stuff is frustrating. i'm really clueless as to what to do next, if anyone could please give me some helpful advice i would really appreciate it. thank you all.

    i'm new to java this is my first java course and this
    stuff is frustrating. i'm really clueless as to what
    to do nextMaybe it's because you don't have a strategy for what the program is supposed to do? To me it looks like a numerical scheme for finding the squareroot of a number.
    Say the number you want to squarerroot is called value and that you have an approximation called guess. How do you determine whether guess is good enought?
    Well in hasMoreGuesses you check whether,
    (abs(value-guess*guess) < epsilon)
    The above decides if guess is within epsilon of being the squareroot of value.
    When you calculate the next guess in nextGuess why do you loop so many times? Aren't you supposed to make just one new guess like,
    guess = (guess + value/guess)/2.0
    The above generates a new guess based on the fact that guess and value/guess must be on each side of value so that the average of them must be closer too value.
    Now you can put the two together to a complete algoritm like,
    while (hasMoreGuesses()) {
       nextGuess();
    }In each iteration of the loop a new "guess" of the squareroot is generated and this continues until the guess is a sufficiently close approximation of the squareroot.

  • Cannot display square root symbol in cvi

    I don't understand why this would be an issue, but if I'm writing in the source window (with the default font of NIEditor), I cannot display a square root symbol "√" - every time I type alt+251, I get "v". Ok, not a huge deal in the source window, but it is a big deal if THAT is what's being stored in a string variable I'm writing out to a file. Additionally, if I use the following to format a string:
    "Fmt(setpointUOM, "%s<W%cT/P3", 251);", then setpointUOM = "WüT/P3". If I display this variable in a string control, it displays as "W√T/P3", which is correct, but if I use it in a Text Box or save it to a sql database, it displays "WüT/P3" which is unacceptable.
    I've tried changing the fonts but nothing works or I get even stranger results. I've been dealing with/ignoring this since CVI7 and I'm currently at CVI10. Thanks for any help.
    Solved!
    Go to Solution.

    The difference in the display between W√T/P3 and WüT/P3 has to do with the character set that you select for the UI control. From what I can tell, only the OEM code pages map the √ symbol to character 251, so if you want to see √ for that character, you should pick the OEM character set, in that control.
    Entering √ with the keyboard in a CVI window seems like a much more problematic task. When you type Alt+251 on a CVI window, the keyboard driver is converting the 251 to 118 (the letter v). I don't know why it does that, but I noticed that the code that it converts 251 to varies, depending on your input language (which you can change in Control Panel>>Region and Language>>Change keyboards or other input methods). When english is selected in the language bar, it converts it to 118. With other languages, it converts it to other codes. I tried entering the unicode value for √ directly, which is Alt+221A (to enter unicode characters using the keypad, you have to follow the steps described here). But it didn't work. It still converted it to 118. I suspect the keyboard driver is doing this because it tries to map 221A to some symbol that is valid in the code page that corresponds to the input language, isn't able to, and picks what it thinks is the closest match.
    In lots of other applications (but not all) you can type Alt+251 or Alt+221A and it works just fine. This is because those applications accept unicode characters directly. Unfortunately, CVI isn't one of them. It uses code pages (a.k.a. character sets, or multibyte sequences) instead of unicode, and symbols don't have a universal meaning; they depend on the code page.
    Even if all this were not an impediment, you'd still run into the problem that in CVI 2010 you cannot change the font of the CVI source window to use an OEM character set. So, you'd still see it displayed as a v or a ü. In CVI 2012 you can change the change it, and so if you were using CVI 2012 you could conceivably use the clipboard to paste the √, but there is a bug in CVI that is preventing OEM characters from being pasted correctly (I realize the description says that it affects tree tooltips, but it's also generally affecting clipboard operations of some less commonly used character sets).
    So, to make a long story short, I think you should continue entering the code directly with the Fmt function, at least until this bug is fixed. And make sure that all UI controls that need to display this string are using the OEM character set.
    Luis

  • Sampling procedure-Square root n+1

    Hi All,
    I need to calculate the sample size based on the Containers & Square  root n+1.
    How to configure the system & how to maintain the master data to get the sample size.
    User also insisted only the sample size has to be calculated, but he will enter only one composite result entry
    Regards
    Subbu

    Hi Subbu,
    you can use Physical Sample to control the sample Size.
    You must to define a Sample Drawing Procedure (QPV2) as relevant for Container Number, then assign the formula 'Square Root n1´ ( TRUNC(SQRT(P2)1) ) in the partial sample. In this scenario, I suggest you to configure the "Container number' as a mandatory field during the goods receipt once the system will need this information to calculate the sample. For a single result recording, you can define a pooled sample.
    I hope it can help you.
    Best regards,
    Robson

  • Java Help....square root problems...

    im just about done with this program except i have to get the square root of the last method i get and when i put in the side 4 and 2 i get 20 as the answer but i need to find the square root of it...my teacher mentioned the math method and i only have this so far and have no idea wat to do with it java.lang.Math.sqrt();
    //this is my test class with system out puts
         System.out.print("Enter the first smaller side: ");
         s1= console.readDouble();
         System.out.print("Enter the second smaller side: ");
         s2= console.readDouble();
         System.out.println("Hypotenuse= " + haveFun.getHyp(s1, s2));
    //my main class Fun with the method to get hypotenuse
         * get hypotenuse of a right triangle
    public double getHyp(double s1, double s2)
              // put your code here
              return (s1 * s1) + (s2 * s2);
         }

    and have no idea wat to do with it
    java.lang.Math.sqrt();
    Then it's time to read the manual:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Math.html#sqrt(double)

  • Help with square root calculator

    Hi: I am new to Java. Trying to write code for square root calculator of numbers 1-10. Have no idea where to start.

    Using pencil and paper, manually extract the square root of a number, and write down the steps that you use to do that. Create a Java program that does those steps.
    A Java Tutorial is here: http://java.sun.com/docs/books/tutorial/

  • Getting a Square Root Result

    Does anyone have an clever ways to yield a square root result. I can use the ^ feature a business rule or calc script and it validates fine, but then I don't get a result
    ex: I can say 100^.5 and should get a value of 10, but no go.....anyone having a similar type issue? Thanks for any assistance.

    Hyperacle,
    You do not need a positive integer for the power argument in the @POWER(expession, power) function -- it can be any numeric expression. It sounds like you might have a block creation issue if you are seeing #missing. You can enter a value at the particular intersection to create the block. Your calc or business rule should calcluate correctly at this point. I just created a test business rule using the example @POWER(100, .5) and the formula returned 10 in the desired intersection.
    Regards,
    csdjr

  • For square root of biginteger

    Hi everyone,
    would you please tell me the link to get the implementation for one BigInteger's squre root?
    Regards,
    Ping

    Although there are no methods to get the square root in the API, you can go through the recursive solution using basic math operators:
    An = (Al / X + Al)/2 where Al is the last number from the resursion (or initially a guess), X is the number you are trying to find the root of, and An is your next closest answer. By recursively feeding An into Al, each iteration will result in An being closer to the actual square root. Repeat until you are within the error of margin you want. However, for this process to work, you need to have floating point values, so you may have to convert the values to BigDecimal objects first. I haven't been able to test this, so I hope it works.
    -JBoeing

  • Newtonian square root help! im getting a zero!

    Hi guys, this is my first post here, adn I'm taking first level Java. I just recently wrote this code and at first it had 2 errors which i was finally able to debug, and made a clean compile. But now when i run it, it always gives me a zero output. Hope you can enlighten me. I know this code may seem elementary to some here, I'm a newbie, so I hope you guys understand! Thanks! Here's the code...
    public class NewtonianSqRoot
         public static void main (String[]args)
              double num;
              //System.out.println("The square root of " + number + " is " + result);
              System.out.println("The square root is " + newtonian(num));
              System.exit(0);
         public static double newtonian(double number)
              double nextGuess;
              double lastGuess;
              double tolerance = 0.0001;
              String gradeString = JOptionPane.showInputDialog(null, "Please enter a number, \nthe program exits if the input is zero (0)", "Newtonian Square Root", JOptionPane.QUESTION_MESSAGE);
              number = Double.parseDouble(gradeString);
              lastGuess = number;
              for (int count = 0; count < 20; count++)
                   nextGuess = ((number / lastGuess) + lastGuess) / 2.0;
                   if ((number - nextGuess) < tolerance)
                        return nextGuess;
                   else
                        nextGuess = lastGuess;
              //System.exit(0);
              return nextGuess;
    }

    Hi !
    Your logic is wrong.....and your code could definetly give the compiler errors... here is the error free code..
    but, you are getting the same number....
    import javax.swing.JOptionPane;
    public class NewtonianSqRoot
    public static void main (String[]args)
    double num=0.00;
    //System.out.println("The square root of " + number + " is " + result);
    System.out.println("The square root is " + newtonian(num));
    System.exit(0);
    public static double newtonian(double number)
    double nextGuess=0.00;
    double lastGuess=0.00;
    double tolerance = 0.0001;
    String gradeString = JOptionPane.showInputDialog(null, "Please enter a number, \nthe program exits if the input is zero (0)", "Newtonian Square Root", JOptionPane.QUESTION_MESSAGE);
    number = Double.parseDouble(gradeString);
    lastGuess = number;
    for (int count = 0; count < 20; count++)
    nextGuess = ((number / lastGuess) + lastGuess) / 2.0;
    if ((number - nextGuess) < tolerance)
    return nextGuess;
    else
    nextGuess = lastGuess;
    //System.exit(0);
    return nextGuess;
    }

  • Calculator square root event listener

    I am trying to write a calculator using JButtons added onto Jpanels. Getting numbers to add , divide, multilpy etc. is simple enough, but i need to write an event handler for a button which calculates the square root of a given number. This is easy enough if you want the square root of 4,9,16,25 etc but if you enter a number which produces a decimal point value it doesn't work.
    I am trying to do this using a variable "number" which is of type double, but have tried using it as a float, but it still doesn't work! here is my code for handling a click on the Square root JButton.
         if(e.getActionCommand().equals("Sqrt")){
         number = new Double(jtf.getText().trim()).doubleValue();
         double rootNum = 1.000;
         while(rootNum*rootNum <= number){
              double rootTester = rootNum * rootNum;
              if(rootTester == number){
                   jtf.setText(String.valueOf(rootNum));
    rootNum = rootNum+1;

    How about
    double answer = Math.sqrt(number);

Maybe you are looking for

  • Error when using Report Generation Toolkit

    Hi, all, I am using Report generation toolkit to generate a report in either word or excel format. But i even can't run the "new report.vi". It returns an error code of "Bad variable type (-2147352568)", and seems this error comes out from the "call

  • Can I open emagic logic projects in Logic Express 7.2?

    Hi I am recording a band in a few weeks, who have already laid down their (live) drum tracks in a proper studio that uses Emagic Logic. I don't know which version, but he runs it on a G4. I use GarageBand at the moment, but am about to move up to Log

  • Automatically Create An Activities From Opportunity?

    How Automatically Create An Activities From Opportunity use the 'Create Follow-up' '? IF  you have some ideas ,please tell me ,thanks!

  • Database structure documentation tool

    I have been asked to include the database structure of our application in the help. It doesn't look as though there is a tool within RH that will do this but I thought it was worth asking in case it's hidden away somewhere. If not, there are plenty o

  • Keying and Rendering in Premiere Pro - Why does it cut the frame in half when I render?

    I am keying a clip in Adobe Premiere and layering it over another clip. Looks great when I play back in the timelime but for some reason when I render the clip the bottom half of the frame goes missing as if I have cropped it out. If I then edit the