eXept Software AG Logo

Smalltalk/X Webserver

Documentation of class 'ShortFloat':

Home

Documentation
www.exept.de
Everywhere
for:
[back]

Class: ShortFloat


Inheritance:

   Object
   |
   +--Magnitude
      |
      +--ArithmeticValue
         |
         +--Number
            |
            +--LimitedPrecisionReal
               |
               +--ShortFloat

Package:
stx:libbasic
Category:
Magnitude-Numbers
Version:
rev: 1.179 date: 2018/05/14 12:12:45
user: stefan
file: ShortFloat.st directory: libbasic
module: stx stc-classLibrary: libbasic
Author:
Claus Gittinger

Description:


ShortFloats represent rational numbers with limited precision.
They use the C-compiler's 'float' format, which is usually the IEEE single float format.

In contrast to Floats (which use the C-compilers 64bit 'double' format),
ShortFloats give you 32 bit floats.

Notice, that ST/X Floats are what Doubles are in ST-80 and ShortFloats are
ST-80's Floats respectively. The reason was to make ST/X's floats compatible
to bothe visualWorks and other smalltalks, which use C-doubles for the Float class
(i.e. VisualST and V'Age).
Thus, STX's Float precision is not worse than that of other ST's.

WARNING:
    The layout of shortFloat instances is known by the runtime system and the compiler;
    you may not add instance variables here.
    Also, subclassing is complicated by the fact, that the VM creates floats/shortFloats,
    and does some of its float-checks by an identity compare with the ShortFloat-class.
    (i.e. your subclasses instances may not be recognized as float-like objects,
     thus mixed mode arithmetic will always coerce them, effectively slowing things down).
    This may be changed, to use a flag bit in the class.

Mixed mode arithmetic:
    shortFloat op shortFloat   -> shortFloat
    shortFloat op fix         -> shortFloat
    shortFloat op fraction    -> shortFloat
    shortFloat op integer     -> shortFloat
    shortFloat op longFloat   -> longFloat
    shortFloat op float       -> float
    shortFloat op complex     -> complex

Representation:
        32bit single precision IEEE floats
        23 bit mantissa,
        8 bit exponent,
        6 decimal digits (approx)

Range and Precision of Storage Formats: see LimitedPrecisionReal >> documentation


Related information:

    Number
    Float
    LongFloat
    Fraction
    FixedPoint
    Integer
    Complex
    FloatArray
    DoubleArray

Class protocol:

accessing
o  defaultPrintFormat

o  defaultPrintFormat: aString

o  epsilon
return the maximum relative spacing of instances of mySelf
(i.e. the value-delta of the least significant bit)

binary storage
o  readBinaryIEEESingleFrom: aStream
read a float value from the binary stream, aStream,
interpreting the next bytes as an IEEE formatted 4-byte float.
The bytes are read in the native byte order (i.e.lsb on intel)

o  readBinaryIEEESingleFrom: aStream MSB: msbFirst
read a float value from the binary stream, aStream,
interpreting the next bytes as an IEEE formatted 4-byte float.
The bytes are read in the soecified byte order

o  readBinaryIEEESingleFrom: aStream into: aBasicNewShortFloat
read a float value from the binary stream, aStream,
interpreting the next bytes as an IEEE formatted 4-byte float.
The bytes are read in the native byte order (i.e.lsb on intel)

o  readBinaryIEEESingleFrom: aStream into: aBasicNewShortFloat MSB: msb
read a float value from the binary stream, aStream,
interpreting the next bytes as an IEEE formatted 4-byte float.
If msb is true, the stream bytes are most-significant-first.

o  storeBinaryIEEESingle: aFloat on: aStream
store aFloat as an IEEE formatted 4-byte float
onto the binary stream, aStream.
The bytes are written in the native byte order (i.e.lsb on intel)

o  storeBinaryIEEESingle: aFloat on: aStream MSB: msb
store aFloat as an IEEE formatted 4-byte float
onto the binary stream, aStream.
If msb is true, the stream bytes are written most-significant-first.

class initialization
o  initialize
print 7 valid digits
usage example(s):
     self initialize

coercing & converting
o  coerce: aNumber
convert the argument aNumber into an instance of the receiver's class and return it.

constants
o  NaN
return a shortFloat which represents not-a-Number (i.e. an invalid number)

o  e
return the constant e as ShortFloat

o  emax
Answer the maximum exponent for this representation.

o  emin
Answer the minimum exponent for this representation.

o  infinity
return a shortFloat which represents positive infinity

o  ln10
return the natural logarithm of 10 as a shortFloat
usage example(s):
     self ln10

o  negativeInfinity
return a shortFloat which represents negative infinity

o  pi
return the constant pi as ShortFloat

o  unity
return the neutral element for multiplication (1.0) as ShortFloat

o  zero
return the neutral element for addition (0.0) as ShortFloat

instance creation
o  basicNew
return a new shortFloat - here we return 0.0
- shortFloats are usually NOT created this way ...
Its implemented here to allow things like binary store & load
of shortFloats. (but even this support will go away eventually, its not
a good idea to store the bits of a float - the reader might have a
totally different representation - so floats will eventually be
binary stored in a device independent format.

o  fastFromString: aString at: startIndex
return the next ShortFloat from the string starting at startIndex.
No spaces are skipped.

This is a specially tuned entry (using a low-level C-call), which
returns garbage if the argument string is not a valid float number.
It has been added to allow higher speed string decomposition into numbers,
especially for mass-data.
usage example(s):
     ShortFloat fastFromString:'123.45' at:1
     ShortFloat fastFromString:'123.45' at:2
     ShortFloat fastFromString:'123.45E4' at:1
     ShortFloat fastFromString:'hello123.45E4' at:6
     ShortFloat fastFromString:'12345' at:1
     ShortFloat fastFromString:'12345' at:2
     ShortFloat fastFromString:'12345' at:3
     ShortFloat fastFromString:'12345' at:4
     ShortFloat fastFromString:'12345' at:5
     ShortFloat fastFromString:'12345' at:6
     ShortFloat fastFromString:'12345' at:0
     ShortFloat fastFromString:'hello123.45E4' at:1

     Time millisecondsToRun:[
	100000 timesRepeat:[
	    ShortFloat readFrom:'123.45'
	]
     ]
usage example(s):
     Time millisecondsToRun:[
	100000 timesRepeat:[
	    ShortFloat fastFromString:'123.45' at:1
	]
     ]

o  fromIEEE32Bit: anInteger
creates a float, given the four native float bytes as an integer
usage example(s):
	ShortFloat fromIEEE32Bit:(#[64 73 15 219] asInteger)

queries
o  defaultPrintPrecision
return the number of decimal digits printed by default
usage example(s):
     ShortFloat defaultPrintPrecision
     Float defaultPrintPrecision
     LongFloat defaultPrintPrecision

o  exponentCharacter

o  isBuiltInClass
return true if this class is known by the run-time-system.
Here, true is returned for myself, false for subclasses.

o  numBitsInExponent
answer the number of bits in the exponent
This is an IEEE float, where 8 bits are available:
seeeeeee emmmmmmm mmmmmmmm mmmmmmmm

o  numBitsInMantissa
answer the number of bits in the mantissa.
This is an IEEE float, where 23 bits (the hidden one is not counted here) are available:
seeeeeee emmmmmmm mmmmmmmm mmmmmmmm

o  precision
answer the precision of a ShortFloat (in bits)
This is an IEEE float, where only the fraction from the normalized mantissa is stored
and so there is a hidden bit and the mantissa is actually represented by 24 binary digits
(although only 23 are needed in the binary representation)
usage example(s):
     self numBitsInMantissa + 1
     self precision

o  radix
answer the radix of a ShortFloats exponent
This is an IEEE float, which is represented as binary


Instance protocol:

arithmetic
o  * aNumber
return the product of the receiver and the argument.

o  + aNumber
return the sum of the receiver and the argument, aNumber

o  - aNumber
return the difference of the receiver and the argument, aNumber

o  / aNumber
return the quotient of the receiver and the argument, aNumber

o  abs
return the absolute value of the receiver
reimplemented here for speed
usage example(s):
     3.0 asShortFloat abs
     -3.0 asShortFloat abs

o  negated
return myself negated

o  rem: aNumber
return the floating point remainder of the receiver and the argument, aNumber

o  uncheckedDivide: aNumber
return the quotient of the receiver and the argument, aNumber.
Do not check for divide by zero (return NaN or Infinity).
This operation is provided for emulators of other languages/semantics,
where no exception is raised for these results (i.e. Java).
It is only defined if the argument's type is the same as the receiver's.
usage example(s):
      0.0 asShortFloat uncheckedDivide:0
      1.0 asShortFloat uncheckedDivide:0.0

coercing & converting
o  asFloat
return a Float with same value as the receiver.
Redefined for performance (machine can do it faster)
usage example(s):
     1.0 asShortFloat asFloat

o  asInteger
return an integer with same value - might truncate
usage example(s):
     12345.0 asShortFloat asInteger
     1e15 asShortFloat asInteger

o  asLongFloat
return a LongFloat with same value as the receiver

o  asShortFloat
return a ShortFloat with same value as the receiver - that's me

o  coerce: aNumber
convert the argument aNumber into an instance of the receiver's class and return it.

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

comparing
o  < aNumber
return true, if the argument is greater

o  <= aNumber
return true, if the argument is greater or equal

o  = aNumber
return true, if the argument represents the same numeric value
as the receiver, false otherwise

o  > aNumber
return true, if the argument is less

o  >= aNumber
return true, if the argument is less or equal

o  hash
return a number for hashing; redefined, since floats compare
by numeric value (i.e. 3.0 = 3), therefore 3.0 hash must be the same
as 3 hash.
usage example(s):
     1.2345 hash
     1.2345 asShortFloat hash
     1.0 hash
     1.0 asShortFloat hash
     0.5 asShortFloat hash
     0.25 asShortFloat hash
     0.5 hash
     0.25 hash

o  isAlmostEqualTo: aNumber nEpsilon: nE
return true, if the argument, aNumber represents almost the same numeric value
as the receiver, false otherwise.

nE is the number of minimal float distances, that the numbers may differ and
still be considered equal.

For background information why floats need this
read: http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

usage example(s):
        67329.234 asShortFloat isAlmostEqualTo:67329.23401 asShortFloat nEpsilon:1
        1.0 asShortFloat isAlmostEqualTo:1.0000001 asShortFloat nEpsilon:1
        1.0 asShortFloat isAlmostEqualTo:1.0000001  nEpsilon:1
        1.0 asShortFloat isAlmostEqualTo:-1.0 nEpsilon:1
        1.0 asShortFloat isAlmostEqualTo:1 nEpsilon:1
        0.0 asShortFloat isAlmostEqualTo:0.0000001 asShortFloat nEpsilon:1
        0.0 asShortFloat isAlmostEqualTo:0.000001 asShortFloat nEpsilon:1
        0.0 asShortFloat isAlmostEqualTo:self epsilon nEpsilon:1
        0.0 asShortFloat - 1.192093e-07 asShortFloat

o  ~= aNumber
return true, if the arguments value are not equal

mathematical functions
o  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/
usage example(s):
     10.0 asShortFloat fastInverseSqrt
     (1 / 10.0 asShortFloat sqrt)

o  ln
return the natural logarithm of the receiver.
Raises an exception, if the receiver is less or equal to zero.
usage example(s):
     0 asFloat ln
     Number trapInfinity:[ 0 asFloat ln ]

     10 asFloat ln       2.30258509299405
     10 asShortFloat ln  2.302585
     10 asLongFloat ln   2.302585092994045684
     10 asQDouble ln     2.30258509299404568402

     50 asFloat ln       3.91202300542815
     50 asShortFloat ln  3.912023
     50 asLongFloat ln   3.912023005428146059
     50 asQDouble ln     3.91202300542814605862

o  log10
return the base-10 logarithm of the receiver.
Raises an exception, if the receiver is less or equal to zero.
usage example(s):
     0 asShortFloat log10
     Number trapInfinity:[ 0 asShortFloat log10 ]

     10 asFloat log10       1.0
     10 asShortFloat log10  1.0
     10 asLongFloat log10   1.0
     10 asQDouble log10     1.00000000000000000000000000000000000000000

     50 asFloat log10       1.69897000433602
     50 asShortFloat log10  1.69897
     50 asLongFloat log10   1.698970004336018805
     50 asQDouble log10     1.69897000433601880478626110527550697323181

printing & storing
o  printOn: aStream
append a printed representation of the receiver to
the argument, aStream.

I use #printString instead of #printOn: as basic print mechanism.

o  printString
return a printed representation of the receiver
LimitedPrecisonReal and its subclasses use #printString instead of
#printOn: as basic print mechanism.
usage example(s):
	1.234 asShortFloat printString.
	1.0 asShortFloat printString.
	1e10 asShortFloat printString.
	1.2e3 asShortFloat printString.
	1.2e30 asShortFloat printString.
	(1.0 uncheckedDivide:0) asShortFloat printString.
	(0.0 uncheckedDivide:0) asShortFloat printString.
	self pi printString.

	self pi printString.
	DefaultPrintFormat := '.3'.
	self pi printString.
	DefaultPrintFormat := '.7'.

	DecimalPointCharacterForPrinting := $,.
	1.234 asShortFloat printString.
	1.0 asShortFloat printString.
	1e10 asShortFloat printString.
	1.2e3 asShortFloat printString.
	1.2e30 asShortFloat printString.
	(1.0 uncheckedDivide:0) asShortFloat printString.
	(0.0 uncheckedDivide:0) asShortFloat printString.
	DecimalPointCharacterForPrinting := $.

o  printStringWithFormat: format
return a printed representation of the receiver;
fmt must be of the form: .nn, where nn is the number of digits.
To print 6 valid digits, use printStringWithFormat:'.6'
For Floats, the default used in printString, is 15 (because its a double);
for ShortFloats, it is 6 (because it is a float)

o  printfPrintString: formatString
non-standard: return a printed representation of the receiver
as specified by formatString, which is defined by printf.

If you use this, be aware, that the format string must be correct and something like %f.
Also, the resulting string may not be longer than 255 bytes -
since that's the (static) size of the buffer.

This method is NONSTANDARD and may be removed without notice.
WARNNG: this goes directly to the C-printf function and may therefore me inherently unsafe.
Please use the printf: method, which is safe as it is completely implemented in Smalltalk.
usage example(s):
ShortFloat pi printfPrintString:'%%lg -> %lg'
usage example(s):
ShortFloat pi printfPrintString:'%%lf -> %lf'
usage example(s):
ShortFloat pi printfPrintString:'%%7.5lg -> %7.5lg'
usage example(s):
ShortFloat pi printfPrintString:'%%G -> %G'
usage example(s):
ShortFloat pi printfPrintString:'%%F -> %F'
usage example(s):
ShortFloat pi printfPrintString:'%%7.5G -> %7.5G'
usage example(s):
ShortFloat pi printfPrintString:'%%7.5F -> %7.5F'

o  storeOn: aStream
append a printed representation of the receiver to
the argument, aStream.

I use #storeString instead of #storeOn: as basic store mechanism.

o  storeString
return a printed representation of the receiver;
all valid digits are printed.
LimitedPrecisonReal and its subclasses use #storeString instead of
#storeOn: as basic print mechanism.
usage example(s):
	0.1 asShortFloat storeString
	((Array new:10 withAll:0.1 asShortFloat) inject:0 into:[:v :sumSoFar| sumSoFar + v]) storeString
	1.0 asShortFloat storeString
	1.234 asShortFloat storeString
	1e10 asShortFloat storeString
	1.2e3 asShortFloat storeString
	1.2e30 asShortFloat storeString
	Float pi asShortFloat storeString
	(1.0 uncheckedDivide:0) asShortFloat storeString
	(0.0 uncheckedDivide:0) asShortFloat storeString

     notice that the storeString is NOT affected by DecimalPointCharacterForPrinting:

	DecimalPointCharacterForPrinting := $,.
	1.234 asShortFloat storeString.
	1.0 asShortFloat storeString.
	1e10 asShortFloat storeString.
	1.2e3 asShortFloat storeString.
	1.2e30 asShortFloat storeString.
	(1.0 uncheckedDivide:0) asShortFloat storeString.
	(0.0 uncheckedDivide:0) asShortFloat storeString.
	DecimalPointCharacterForPrinting := $.

private accessing
o  basicAt: index
return an internal byte of the float.
The value returned here depends on byte order, float representation etc.
Therefore, this method should be used strictly private.

Notice:
the need to redefine this method here is due to the
inability of many machines to store floats in non-double aligned memory.
Therefore, on some machines, the first 4 bytes of a float are left unused,
and the actual float is stored at index 5 .. 12.
To hide this at one place, this method knows about that, and returns
values as if this filler wasnt present.

o  basicAt: index put: value
set an internal byte of the float.
The value to be stored here depends on byte order, float representation etc.
Therefore, this method should be used strictly private.

Notice:
the need to redefine this method here is due to the
inability of many machines to store floats in non-double aligned memory.
Therefore, on some machines, the first 4 bytes of a float are left unused,
and the actual float is stored at index 5 .. 12.
To hide this at one place, this method knows about that, and returns
values as if this filler wasnt present.

private-accessing
o  byteAt: index

o  byteAt: index put: newByte

queries
o  nextFloat: count
answer the next float count places after (or before if count is negative) myself
usage example(s):
     (1.0 asShortFloat nextFloat:2) storeString
     (67329.234 asShortFloat nextFloat:1) storeString
     ShortFloat NaN nextFloat:100000
     ShortFloat infinity nextFloat:100000

special access
o  exponent
extract a normalized float's exponent.
The returned value depends on the float-representation of
the underlying machine and is therefore highly unportable.
This is not for general use.
This assumes that the mantissa is normalized to
0.5 .. 1.0 and the float's value is mantissa * 2^exp
usage example(s):
     4.0 asShortFloat exponent
     2.0 asShortFloat exponent
     1.0 asShortFloat exponent
     0.5 asShortFloat exponent
     0.25 asShortFloat exponent
     0.00000011111 asShortFloat exponent

o  mantissa
extract a normalized floats mantissa.
The returned value depends on the float-representation of
the underlying machine and is therefore highly unportable.
This is not for general use.
This assumes that the mantissa is normalized to
0.5 .. 1.0 and the floats value is mantissa * 2^exp
usage example(s):
     1.0 asShortFloat exponent
     1.0 asShortFloat mantissa
     1e1000 asShortFloat mantissa

     0.5 asShortFloat exponent
     0.5 asShortFloat mantissa

     0.25 asShortFloat exponent
     0.25 asShortFloat mantissa

     0.00000011111 asShortFloat exponent
     0.00000011111 asShortFloat mantissa

testing
o  isFinite
return true, if the receiver is a finite float
i.e. not NaN and not infinite.
usage example(s):
	1.0 asShortFloat isFinite
	(0.0 asShortFloat uncheckedDivide: 0.0) isFinite
	(1.0 asShortFloat uncheckedDivide: 0.0) isFinite

o  isNaN
return true, if the receiver is an invalid float (NaN - not a number).
These are not created by ST/X float operations (they raise an exception);
however, inline C-code could produce them ...
usage example(s):
     1.0 asShortFloat isNaN
     (0.0 asShortFloat uncheckedDivide: 0.0) isNaN
     (0.0 asShortFloat uncheckedDivide: 0.0 asShortFloat) isNaN

o  isNegativeZero
many systems have two float.Pnt zeros
usage example(s):
     0.0 asShortFloat isNegativeZero
     -0.0 asShortFloat isNegativeZero

o  negative
return true if the receiver is less than zero.
-0.0 is positive for now.
usage example(s):
	0.0 asShortFloat negative
	-0.0 asShortFloat negative
	1.0 asShortFloat negative
	-1.0 asShortFloat negative
	(1.0 uncheckedDivide: 0.0) asShortFloat negative
	(-1.0 uncheckedDivide: 0.0) asShortFloat negative

o  numberOfBits
return the size (in bits) of the real;
typically, 32 is returned here,
but who knows ...
usage example(s):
     1.2 numberOfBits
     1.2 asShortFloat numberOfBits

o  positive
return true if the receiver is greater or equal to zero (not negative)
0.0 and -0.0 are positive for now.
usage example(s):
	0.0 asShortFloat positive
	-0.0 asShortFloat positive
	1.0 asShortFloat positive
	-1.0 asShortFloat positive
	(1.0 uncheckedDivide: 0.0) asShortFloat positive
	(-1.0 uncheckedDivide: 0.0) asShortFloat positive

o  strictlyPositive
return true if the receiver is greater than zero

truncation & rounding
o  ceiling
return the smallest integer which is greater or equal to the receiver.
usage example(s):
     0.5 asShortFloat ceiling
     -0.5 asShortFloat ceiling

o  ceilingAsFloat
return the smallest integer-valued float greater or equal to the receiver.
This is much like #ceiling, but avoids a (possibly expensive) conversion
of the result to an integer.
It may be useful, if the result is to be further used in another float-operation.
usage example(s):
     0.5 asShortFloat ceilingAsFloat
     -0.5 asShortFloat ceilingAsFloat
     -1.5 asShortFloat ceilingAsFloat

o  floor
return the integer nearest the receiver towards negative infinity.
usage example(s):
     0.5 asShortFloat floor
     -0.5 asShortFloat floor

o  floorAsFloat
return the float which represents the next lower
integer nearest the receiver towards negative infinity.
Much like floor, but returns a float result - useful if the result
will be used in another float operation, to avoid costy int-conversion.
usage example(s):
     0.5 asShortFloat floorAsFloat
     -0.5 asShortFloat floorAsFloat

o  fractionPart
extract the after-decimal fraction part.
such that (self truncated + self fractionPart) = self
usage example(s):
     1.6 asShortFloat fractionPart + 1.6 asShortFloat truncated
     -1.6 asShortFloat fractionPart + -1.6 asShortFloat truncated

     1.0 asShortFloat fractionPart
     0.5 asShortFloat fractionPart
     0.25 asShortFloat fractionPart
     3.14159 asShortFloat fractionPart
     12345673.14159 asShortFloat fractionPart
     123456731231231231.14159 asShortFloat fractionPart

o  rounded
return the receiver rounded to the nearest integer
usage example(s):
     0.4 asShortFloat rounded
     0.5 asShortFloat rounded
     0.6 asShortFloat rounded
     -0.4 asShortFloat rounded
     -0.5 asShortFloat rounded
     -0.6 asShortFloat rounded
     1e32 asShortFloat rounded

o  roundedAsFloat
return the receiver rounded to the nearest integer as a float.
This is much like #rounded, but avoids a (possibly expensive) conversion
of the result to an integer.
It may be useful, if the result is to be further used in another float-operation.
usage example(s):
     0.4 asShortFloat rounded
     0.5 asShortFloat rounded
     0.6 asShortFloat rounded
     -0.4 asShortFloat rounded
     -0.5 asShortFloat rounded
     -0.6 asShortFloat rounded

     0.4 asShortFloat roundedAsFloat
     0.5 asShortFloat roundedAsFloat
     0.6 asShortFloat roundedAsFloat
     -0.4 asShortFloat roundedAsFloat
     -0.5 asShortFloat roundedAsFloat
     -0.6 asShortFloat roundedAsFloat

o  truncated
return the receiver truncated towards zero as an integer
usage example(s):
     0.5 asShortFloat truncated
     -0.5 asShortFloat truncated
     0.5 asShortFloat truncatedAsFloat
     -0.5 asShortFloat truncatedAsFloat

o  truncatedAsFloat
return the receiver truncated towards zero as a float.
This is much like #truncated, but avoids a (possibly expensive) conversion
of the result to an integer.
It may be useful, if the result is to be further used in another
float-operation.
usage example(s):
     0.5 asShortFloat truncated
     -0.5 asShortFloat truncated
     0.5 asShortFloat truncatedAsFloat
     -0.5 asShortFloat truncatedAsFloat



ST/X 7.1.0.0; WebServer 1.663 at exept.de:8081; Mon, 20 Aug 2018 15:01:41 GMT