Mantis - Squeak
Viewing Issue Advanced Details
7099 Kernel feature N/A 06-17-08 22:01 06-23-08 20:10
nicolas cellier  
 
normal  
new 3.10  
open  
none    
none  
0007099: [FEATURE] Integer>>sqrtTruncated and sqrtRounded
It can be done in Integer arithmetic and implementation is fast.
And it won't suffer any potential inexact arithmetic problem raised by Float conversion...

That's why i prefer (x sqrtTruncated) to (x sqrt truncated)...

TODO: implement for rationals...
 Integer-sqrtTruncated-M7099.1.cs [^] (1,918 bytes) 06-17-08 23:13
 Integer-sqrtTruncated-Test-M7099.1.cs [^] (2,138 bytes) 06-17-08 23:14
 Integer-sqrtTruncated-Test-M7099.2.cs [^] (1,640 bytes) 06-17-08 23:17
 Fraction-sqrtTruncated-M7099.1.cs [^] (2,239 bytes) 06-18-08 00:44
 Fraction-sqrtTruncated-Test-M7099.1.cs [^] (1,258 bytes) 06-18-08 00:44

Notes
(0012300)
nicolas cellier   
06-17-08 23:18   
Wrong changeset handling...
Integer-sqrtTruncated-Test-M7099.1.cs incorrectly includes/duplicates some methods from Integer-sqrtTruncated-M7099.1.cs

That's why there is a Integer-sqrtTruncated-Test-M7099.2.cs
(0012301)
nicolas cellier   
06-17-08 23:24   
When i think of it, raising a FloatingPointException in an integer arithmetic method is not the nicest thing to do!

This exception should better be renamed as an ArithmeticException.
(0012302)
nicolas cellier   
06-18-08 00:24   
A good example of intermediate inexact arithmetic failure:

| x |
x := (1 bitShift: 53).
self assert: (x + (1/2)) squared sqrtRounded = (x+1)

fails if implemented asFloat sqrt rounded

I provide hereafter a first Fraction implementation

(0012307)
nicolas cellier   
06-23-08 20:10   
Andres Valloud who initiated my answer at http://groups.google.am/group/comp.lang.smalltalk/browse_thread/thread/179b982ac8562ccf [^] has posted on his blog a simular solution (See http://blogten.blogspot.com/2008/06/update-on-sqrtrounded.html) [^] :

sqrtRounded
    | x |
    x := (self * 4) sqrtTruncated.
    ^(x//2) + (x\\2)

which can also be written (may be more efficiently)

sqrtRounded
    | x |
    x := (self bitShift: 2) sqrtTruncated.
    ^(x bitShift: -1) + (x bitAnd: 1)