Number.st
author Claus Gittinger <cg@exept.de>
Tue, 18 Dec 2001 14:46:21 +0100
changeset 6335 8286bc57d05e
parent 6258 435600a44e73
child 6345 cfe5db4fe391
permissions -rw-r--r--
closeTo: generalized for all numbers

"
 COPYRIGHT (c) 1988 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"

"{ Package: 'stx:libbasic' }"

ArithmeticValue subclass:#Number
	instanceVariableNames:''
	classVariableNames:''
	poolDictionaries:''
	category:'Magnitude-Numbers'
!

!Number class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1988 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
!

documentation
"
    abstract superclass for all kinds of numbers

    [author:]
	Claus Gittinger

    [see also:]
	Integer LargeInteger SmallInteger
	LimitedPrecisionReal Float ShortFloat
	Fraction FixedPoint
"
! !

!Number class methodsFor:'instance creation'!

fromString:aString
    "for compatibility with other smalltalks - same as #readFrom:"

    ^ self readFrom:aString

    "
     Number fromString:'12345'
     '12345' asNumber
    "

    "Modified: / 3.8.1998 / 20:05:11 / cg"
!

fromString:aString onError:exceptionBlock
    "for compatibility with other smalltalks - same as #readFrom:"

    ^ self readFrom:aString onError:exceptionBlock

    "
     Number fromString:'12345' onError:0
     Number fromString:'fooBarBaz' onError:0
    "

    "Modified: / 3.8.1998 / 20:05:34 / cg"
!

readFrom:aStringOrStream onError:exceptionBlock
    "return the next Number from the (character-)stream aStream;
     skipping all whitespace first; return the value of exceptionBlock,
     if no number can be read."

    |value|

    ErrorSignal handle:[:ex |
	^ exceptionBlock value
    ] do:[
	|str nextChar radix negative signExp|

	str := aStringOrStream readStream.

	nextChar := str skipSeparators.
	nextChar isNil ifTrue:[^ exceptionBlock value].

	(nextChar == $-) ifTrue:[
	    negative := true.
	    str next.
	    nextChar := str peekOrNil
	] ifFalse:[
	    negative := false.
	    (nextChar == $+) ifTrue:[
		str next.
		nextChar := str peekOrNil
	    ]
	].
	(nextChar isDigit or:[nextChar == $.]) ifFalse:[
	    ^ exceptionBlock value.
"/          value := super readFrom:str.
"/          negative ifTrue:[value := value negated].
"/          ^ value
	].
	nextChar == $. ifTrue:[
	    radix := 10.
	    value := 0.0.
	] ifFalse:[
	    value := Integer readFrom:str radix:10.
	    nextChar := str peekOrNil.
	    ((nextChar == $r) or:[ nextChar == $R]) ifTrue:[
		str next.
		radix := value.
		value := Integer readFrom:str radix:radix.
	    ] ifFalse:[
		radix := 10
	    ].
	].

	(nextChar == $.) ifTrue:[
	    str next.
	    nextChar := str peekOrNil.
	    (nextChar notNil and:[nextChar isDigitRadix:radix]) ifTrue:[
		value := value asFloat 
			 + (Number readMantissaFrom:str radix:radix).
		nextChar := str peekOrNil
	    ]
	].
	((nextChar == $e) or:[nextChar == $E]) ifTrue:[
	    str next.
	    nextChar := str peekOrNil.
	    signExp := 1.
	    (nextChar == $+) ifTrue:[
		str next.
		nextChar := str peekOrNil.
	    ] ifFalse:[
		(nextChar == $-) ifTrue:[
		    str next.
		    nextChar := str peekOrNil.
		    signExp := -1
		]
	    ].
	    (nextChar notNil and:[(nextChar isDigitRadix:radix)]) ifTrue:[
		value := value asFloat 
			 * (10.0 raisedToInteger:
				    ((Integer readFrom:str radix:radix) * signExp))
	    ]
	].
	negative ifTrue:[
	    value := value negated
	].
    ].
    ^ value.

    "
     Number readFrom:(ReadStream on:'54.32e-01')      
     Number readFrom:(ReadStream on:'12345678901234567890') 
     Number readFrom:(ReadStream on:'16rAAAAFFFFAAAAFFFF') 
     Number readFrom:'16rAAAAFFFFAAAAFFFF' 
     Number readFrom:'0.000001'  
     '+00000123.45' asNumber  
    "

    "Modified: / 14.4.1998 / 19:22:50 / cg"
!

readSmalltalkSyntaxFrom:aStream
    "ST-80 compatibility (thanks to a note from alpha testers)
     read and return the next Number in smalltalk syntax from the 
     (character-)stream aStream."

    ^ Scanner scanNumberFrom:aStream
"/    ^ Compiler evaluate:aStream compile:false "/ self readFrom:aStream.

    "
     Number readSmalltalkSyntaxFrom:(ReadStream on:'54.32e-01')    
     Number readSmalltalkSyntaxFrom:(ReadStream on:'12345678901234567890')
     Number readSmalltalkSyntaxFrom:(ReadStream on:'16rAAAAFFFFAAAAFFFF')
     Number readSmalltalkSyntaxFrom:(ReadStream on:'(1/10)') 
     Number readFrom:(ReadStream on:'(1/10)') 
     Number readSmalltalkSyntaxFrom:(ReadStream on:'+00000123.45')  
     Number readFrom:(ReadStream on:'+00000123.45')  

     |s|
     s := ReadStream on:'2.'.
     Number readSmalltalkSyntaxFrom:s.
     s next    

     |s|
     s := ReadStream on:'2.0.'.
     Number readSmalltalkSyntaxFrom:s.
     s next    
    "

    "Modified: / 19.11.1999 / 18:26:47 / cg"
! !

!Number class methodsFor:'error reporting'!

raise:aSignalSymbolOrErrorClass receiver:someNumber selector:sel arg:arg errorString:text 
    "ST-80 compatible signal raising. Provided for PD numeric classes"

    <context: #return>

    ^ self
        raise:aSignalSymbolOrErrorClass 
        receiver:someNumber 
        selector:sel 
        arguments:(Array with:arg)
        errorString:text 

    "
     Number 
        raise:#domainErrorSignal
        receiver:1.0
        selector:#sin
        arg:nil
        errorString:'foo bar test'
    "

    "Modified: / 16.11.2001 / 14:12:50 / cg"
!

raise:aSignalSymbolOrErrorClass receiver:someNumber selector:sel arguments:argArray errorString:text 
    "ST-80 compatible signal raising. Provided for PD numeric classes.
     aSignalSymbolOrErrorClass is either an Error-subclass, or
     the selector which is sent to myself, to retrieve the Exception class / Signal."

    <context: #return>

    |msg signalOrException|

    msg := MessageSend
                receiver:someNumber
                selector:sel
                arguments:argArray.

    aSignalSymbolOrErrorClass isSymbol ifTrue:[
        signalOrException := self perform:aSignalSymbolOrErrorClass.
    ] ifFalse:[
        signalOrException := aSignalSymbolOrErrorClass.    "/ assume its an Error-Subclass
    ].

    ^ signalOrException
         raiseRequestWith:msg 
         errorString:text 
         in:thisContext sender

    "
     Number 
        raise:#domainErrorSignal
        receiver:1.0
        selector:#foo 
        errorString:'foo bar test'
    "

    "Modified: / 16.11.2001 / 14:12:09 / cg"
!

raise:aSignalSymbolOrErrorClass receiver:someNumber selector:sel errorString:text 
    "ST-80 compatible signal raising. Provided for PD numeric classes.
     aSignalSymbolOrErrorClass is either an Error-subclass, or
     the selector which is sent to myself, to retrieve the Exception class / Signal."

    <context: #return>

    ^ self
        raise:aSignalSymbolOrErrorClass 
        receiver:someNumber 
        selector:sel 
        arguments:#()
        errorString:text 

    "
     Number 
        raise:#domainErrorSignal
        receiver:1.0
        selector:#foo 
        errorString:'foo bar test'
    "

    "Modified: / 16.11.2001 / 14:13:16 / cg"
! !

!Number class methodsFor:'private'!

readMantissaFrom:aStream radix:radix
    "helper for readFrom: -
     return the mantissa from the (character-)stream aStream;
     no whitespace-skipping; error if no number available"

    |nextChar value factor|

    value := 0.0.
    factor := 1.0 / radix.
    nextChar := aStream peekOrNil.
    [nextChar notNil and:[nextChar isDigitRadix:radix]] whileTrue:[
	value := value + (nextChar digitValue * factor).
	factor := factor / radix.
	aStream next.
	nextChar := aStream peekOrNil
    ].
    ^ value

    "Modified: / 14.4.1998 / 18:47:47 / cg"
! !

!Number methodsFor:'Compatibility - Squeak'!

asSmallAngleDegrees
	"Return the receiver normalized to lie within the range (-180, 180)"

	| pos |
	pos _ self \\ 360.
	pos > 180 ifTrue: [pos _ pos - 360].
	^ pos

"#(-500 -300 -150 -5 0 5 150 300 500 1200) collect: [:n | n asSmallAngleDegrees]"
!

closeFrom:aNumber
    "are these two numbers close?"

    | fuzz |

    self isNaN == aNumber isNaN ifFalse: [^ false]. 
    self isInfinite == aNumber isInfinite ifFalse: [^ false].

    fuzz := (self abs max:aNumber abs) * 0.0001. 
    ^ (self - aNumber) abs <= fuzz

    "
     9.0 closeTo: 8.9999     
     9.9 closeTo: 9          
     (9/3) closeTo: 2.9999      
     1 closeTo: 0.9999      
     1 closeTo: 1.0001      
     1 closeTo: 1.001       
     1 closeTo: 0.999       

     0.9999 closeTo: 1      
     1.0001 closeTo: 1      
     1.001 closeTo: 1     
     0.999 closeTo: 1     
    "
!

closeTo:num
    "are these two numbers close?"

    ^ num closeFrom:self

    "
     1 closeTo:1.0000000001
     1 closeTo:1.001
    "

    "Created: / 5.11.2001 / 18:07:26 / cg"
!

newTileMorphRepresentative
	^ TileMorph new addArrows; setLiteral: self; addSuffixIfCan
!

stringForReadout
    ^ self rounded printString
! !

!Number methodsFor:'coercing & converting'!

coerce:aNumber
    "return aNumber converted into receivers type"

    ^ self subclassResponsibility
!

generality
    "return the generality value - see ArithmeticValue>>retry:coercing:"

    ^ 40
! !

!Number methodsFor:'converting'!

% aNumber 
    "Return a complex number with the receiver as the real part and 
     aNumber as the imaginary part"

    ^ Complex real:self imaginary:aNumber

    "Modified: / 9.7.1998 / 10:18:12 / cg"
!

@ aNumber
    "return a Point with the receiver as x-coordinate and the argument
     as y-coordinate"

%{  /* NOCONTEXT */

    /*
     * I cannot tell if this special code is worth anything
     */
    if (__CanDoQuickNew(sizeof(struct __Point))) {      /* OBJECT ALLOCATION */
	OBJ newPoint;
	int spc;

	__qCheckedAlignedNew(newPoint, sizeof(struct __Point));
	__InstPtr(newPoint)->o_class = @global(Point);
	__PointInstPtr(newPoint)->p_x = self;
	__PointInstPtr(newPoint)->p_y = aNumber;
	if (! __bothSmallInteger(self, aNumber)) {
	    spc = __qSpace(newPoint);
	    __STORE_SPC(newPoint, aNumber, spc);
	    __STORE_SPC(newPoint, self, spc);
	}
	RETURN ( newPoint );
    }
%}
.
    ^ Point x:self y:aNumber
!

asComplex
    "Return a complex number with the receiver as the real part and 
     zero as the imaginary part"

    ^ Complex fromReal:self

    "Modified: / 9.7.1998 / 10:18:16 / cg"
!

asPoint
    "return a new Point with the receiver as all coordinates;  
     often used to supply the same value in two dimensions, as with 
     symmetrical gridding or scaling."

%{  /* NOCONTEXT */

    if (__CanDoQuickNew(sizeof(struct __Point))) {      /* OBJECT ALLOCATION */
	OBJ newPoint;

	__qCheckedAlignedNew(newPoint, sizeof(struct __Point));
	__InstPtr(newPoint)->o_class = @global(Point);
	__PointInstPtr(newPoint)->p_x = self;
	__PointInstPtr(newPoint)->p_y = self;
	__STORE(newPoint, self);
	RETURN ( newPoint );
    }
%}.
    ^ Point x:self y:self
!

decodeAsLiteralArray
    "given a literalEncoding in the receiver,
     create & return the corresponding object.
     The inverse operation to #literalArrayEncoding."

    ^ self

    "Created: 25.2.1997 / 19:17:06 / cg"
    "Modified: 25.2.1997 / 19:17:42 / cg"
!

degreesToRadians
    "interpreting the receiver as radians, return the degrees"

    ^ (self * (Float pi)) / 180.0
!

literalArrayEncoding
    "encode myself as an array literal, from which a copy of the receiver
     can be reconstructed with #decodeAsLiteralArray."

    ^ self

    "Modified: 1.9.1995 / 02:25:26 / claus"
    "Modified: 22.4.1996 / 13:00:27 / cg"
!

radiansToDegrees
    "interpreting the receiver as degrees, return the radians"

    ^ (self * 180.0) / (Float pi)
! !

!Number methodsFor:'intervals'!

downTo:stop
    "return an interval from receiver down to the argument, incrementing by -1"

    ^ self to:stop by:-1

    "
     (10 downTo:1) do:[:i | Transcript showCR:i].
    "
!

to:stop
    "return an interval from receiver up to the argument, incrementing by 1"

    ^ Interval from:self to:stop
!

to:stop by:step
    "return an interval from receiver up to the argument, incrementing by step"

    ^ Interval from:self to:stop by:step
!

to:stop byFactor:factor
    "return a geometric series from receiver up to the argument;
     elements have a constant factor in between"

    ^ GeometricSeries from:self to:stop byFactor:factor

    "
     (1 to:256 byFactor:2)
     (256 to:1 byFactor:1/2)     
    "
! !

!Number methodsFor:'iteration'!

timesRepeat:aBlock
    "evaluate the argument, aBlock self times"

    |count|

    count := self.
    [count > 0] whileTrue:[
	aBlock value.
	count := count - 1
    ]
! !

!Number methodsFor:'mathematical functions'!

conjugated
    "Return the complex conjugate of this Number."

    ^ self

    "Modified: / 9.7.1998 / 10:17:31 / cg"
!

imaginary
    "Return the imaginary part of this Number."

    ^ 0

    "Modified: / 9.7.1998 / 10:17:24 / cg"
!

real
    "Return the real part of this Number."

    ^ self

    "Modified: / 9.7.1998 / 10:17:17 / cg"
!

timesTwoPower:anInteger
    "Return the receiver multiplied by 2.0 raised to the power of the argument.
     For protocol completeness wrt. Squeak and ST80."

    ^ self * (2.0 raisedToInteger:anInteger)

    "
     123 timesTwoPower:0  
     123 timesTwoPower:1  
     123 timesTwoPower:2  
     123 timesTwoPower:3  
    "
! !

!Number methodsFor:'printing & storing'!

printOn:aStream paddedWith:padCharacter to:size base:radix
    |s|

    s := self printStringRadix:radix.
    s printOn: aStream leftPaddedTo:size with: padCharacter


!

storeOn:aStream
    "append a string for storing the receiver onto the argument,
     aStream - since numbers are literals,they store as they print."

    ^ self printOn:aStream
!

storeString
    "return a string for storing 
     - since numbers are literals, they store as they print."

    ^ self printString
! !

!Number methodsFor:'testing'!

isDivisibleBy:aNumber
    "return true, if the receiver can be divided by the argument, aNumber without a remainder.
     Notice, that the result is only worth trusting, if the receiver is an integer."

    aNumber = 0 ifTrue: [^ false].
    aNumber isInteger ifFalse: [^ false].
    ^ (self \\ aNumber) = 0

    "
     3 isDivisibleBy:2     
     4 isDivisibleBy:2
     4.0 isDivisibleBy:2   
     4.5 isDivisibleBy:4.5 
     4.5 isDivisibleBy:1.0 
    "
!

isInfinite

        ^ false

    "Created: / 5.11.2001 / 18:07:26 / cg"
!

isNaN
    "return true, if the receiver is an invalid float (NaN - not a number)."

    ^ false

    "Created: / 5.11.2001 / 18:07:26 / cg"
!

isNumber
    "return true, if the receiver is a kind of number"

    ^ true
!

isReal
    "return true, if the receiver is some kind of real number (as opposed to a complex);
     true is returned here - the method is redefined from Object."

    ^ true
!

isZero
    "return true, if the receiver is zero"

    ^ self = 0

    "Modified: 18.7.1996 / 12:40:49 / cg"
! !

!Number methodsFor:'tracing'!

traceInto:aRequestor level:level from:referrer
    "double dispatch into tracer, passing my type implicitely in the selector"

    ^ aRequestor traceNumber:self level:level from:referrer


! !

!Number methodsFor:'truncation & rounding'!

detentBy: detent atMultiplesOf: grid snap: snap
    "Map all values that are within detent/2 of any multiple of grid 
     to that multiple.  
     Otherwise, if snap is true, return self, meaning that the values 
     in the dead zone will never be returned.  
     If snap is false, then expand the range between dead zones
     so that it covers the range between multiples of the grid, 
     and scale the value by that factor."

    | r1 r2 |

    r1 := self roundTo: grid.                    "Nearest multiple of grid"
    (self roundTo: detent) = r1 ifTrue: [^ r1].  "Snap to that multiple..."
    snap ifTrue: [^ self].                       "...or return self"

    r2 := self < r1                               "Nearest end of dead zone"
	    ifTrue: [r1 - (detent asFloat/2)]
	    ifFalse: [r1 + (detent asFloat/2)].

    "Scale values between dead zones to fill range between multiples"
    ^ r1 + ((self - r2) * grid asFloat / (grid - detent))

    "
     (170 to: 190 by: 2) collect: [:a | a detentBy: 10 atMultiplesOf: 90 snap: true]         
     (170 to: 190 by: 2) collect: [:a | a detentBy: 10 atMultiplesOf: 90 snap: false]
     (3.9 to: 4.1 by: 0.02) collect: [:a | a detentBy: 0.1 atMultiplesOf: 1.0 snap: true]    
     (-3.9 to: -4.1 by: -0.02) collect: [:a | a detentBy: 0.1 atMultiplesOf: 1.0 snap: false]
    "
!

fractionPart
    "return a float with value from digits after the decimal point.
     (i.e. the receiver minus its truncated value)"

    ^ self - self truncated asFloat

    "
     1234.56789 fractionPart
     1.2345e6 fractionPart  
    "

    "Modified: / 4.11.1996 / 20:26:54 / cg"
    "Created: / 28.10.1998 / 17:14:40 / cg"
!

integerPart
    "return a float with value from digits before the decimal point
     (i.e. the truncated value)"

    ^ self truncated asFloat

    "
     1234.56789 integerPart 
     1.2345e6 integerPart   
     12.5 integerPart 
     -12.5 integerPart 
     (5/3) integerPart  
     (-5/3) integerPart 
     (5/3) truncated  
     (-5/3) truncated  
    "

    "Created: / 28.10.1998 / 17:14:56 / cg"
    "Modified: / 5.11.2001 / 17:54:22 / cg"
! !

!Number class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libbasic/Number.st,v 1.71 2001-12-18 13:46:21 cg Exp $'
! !