--- a/ShortFloat.st Fri Jun 03 18:15:16 2011 +0100
+++ b/ShortFloat.st Wed Jun 08 22:53:07 2011 +0100
@@ -928,6 +928,66 @@
^ super ~= aNumber
! !
+!ShortFloat methodsFor:'mathematical functions'!
+
+fastInverseSqrt
+ "return a rough but fast approximation of (1 / self sqrt).
+ The error is some 1%, which is ok for many 3D computations or physics simulations.
+ Do not use this for now: it is non-portable and probably not speeding things up
+ much, unless inlined into the sender code.
+ The code is here as a reminder and might be later used as a hint for the inliner
+ (to speed up 3D computations, for example).
+ see: http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/"
+
+%{ /* NOCONTEXT */
+ float x, rslt;
+ OBJ newFloat;
+
+ if (sizeof(float) == 4) {
+ x = __shortFloatVal(self);
+ {
+ float xhalf = 0.5f * x;
+ int i = *(int*)&x; // store floating-point bits in integer
+
+ i = 0x5f3759d5 - (i >> 1); // initial guess for Newton's method
+ x = *(float*)&i; // convert new bits into float
+ x = x*(1.5f - xhalf*x*x); // One round of Newton's method
+ __qMKSFLOAT(newFloat, x);
+ RETURN ( newFloat );
+ }
+ }
+%}.
+ ^ 1 / self sqrt
+
+ "
+ 10.0 asShortFloat fastInverseSqrt
+ (1 / 10.0 asShortFloat sqrt)
+ "
+
+ "
+ |a b t0 t1 t2|
+
+ a := 345 asShortFloat.
+ t0 := Time millisecondsToRun:[
+ 1000000 timesRepeat:[
+ ]
+ ].
+ t1 := Time millisecondsToRun:[
+ 1000000 timesRepeat:[
+ a fastInverseSqrt
+ ]
+ ].
+ t2 := Time millisecondsToRun:[
+ 1000000 timesRepeat:[
+ (1 / a sqrt)
+ ]
+ ].
+ Transcript show:'empty: '; showCR:t0.
+ Transcript show:'fast: '; showCR:t1.
+ Transcript show:'regular: '; showCR:t2.
+ "
+! !
+
!ShortFloat methodsFor:'printing & storing'!
printString
@@ -1724,15 +1784,15 @@
!ShortFloat class methodsFor:'documentation'!
version
- ^ '$Id: ShortFloat.st 10632 2011-04-09 17:19:04Z vranyj1 $'
+ ^ '$Id: ShortFloat.st 10643 2011-06-08 21:53:07Z vranyj1 $'
!
version_CVS
- ^ 'Header: /var/local/cvs/stx/libbasic/ShortFloat.st,v 1.104 2010-05-05 13:56:55 stefan Exp '
+ ^ 'Header: /cvs/stx/stx/libbasic/ShortFloat.st,v 1.108 2011/05/05 08:57:20 mb Exp '
!
version_SVN
- ^ '$Id: ShortFloat.st 10632 2011-04-09 17:19:04Z vranyj1 $'
+ ^ '$Id: ShortFloat.st 10643 2011-06-08 21:53:07Z vranyj1 $'
! !
@@ -1741,3 +1801,4 @@
+