-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_fixedInt.py
859 lines (633 loc) · 26.9 KB
/
_fixedInt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
##########################################################################
# This file is part of the deModel library, a Python package for using
# Python to model fixed point arithmetic algorithms.
#
# Copyright (C) 2007 Dillon Engineering, Inc.
# http://www.dilloneng.com
#
# The deModel library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
# If not, see <http://www.gnu.org/licenses/>
##########################################################################
'''DeFixedInt class
'''
__author__ = "$Author: guenter $"
__revision__ = "$Revision: 431 $"
__date__ = "$Date: 2007-09-19 19:16:58 +0200 (Wed, 19 Sep 2007) $"
import math
import copy
import numpy
def arrayFixedInt(intWidth, fractWidth, N, value=None):
'''Create a Numpy array of length N with DeFixedInt instances of
representation A(intWidth, fractWidth).
If value is specified the instances are set with the specified value.
@type intWidth : integer
@param intWidth : used bit width for interger part
@type fractWidth : integer
@param fractWidth : used bit width for fractional part
@type N : integer, list, or array
@param N : if N is an integer the value specifies the length of the
array to be created. If N is a list or array, an
array of same length is created with the values
used to initialize the returned array.
@type value : integer or float
@param value : initialize the array with the given value. This
parameter is ommitted if N is a list
@rtype : numpy array
@return : numpy array with N instances of DeFixedInt()
'''
if(isinstance(N, (int, long))):
retA = numpy.array([DeFixedInt(intWidth, fractWidth) for i in range(N)])
if(value):
for i, item in enumerate(retA):
item.value = value
elif(isinstance(N, (list, numpy.ndarray))):
retA = numpy.array([DeFixedInt(intWidth, fractWidth, value) \
for value in N])
else:
raise TypeError("type(N) = '%s' not supported" %type(N))
return retA
class DeFixedIntOverflowError(OverflowError):
"Used to indicate that a set value exceeds the specified width of DeFixedInt."
class DeFixedInt(object):
'''
Fixed point fractional arithmetic data type
===========================================
Introduction
------------
The class is an abstract data type that can be used to perform fixed-
point arithmetic. The data type keeps track of the decimal point and
arithmetic operations affect the position of the decimal point based
on the fundamental rules of fixed-point arithmetic.
The data type is for signed numbers. It can be initiated with an
integer number, then the value is just assigned to the data type. It
also can be initiated with a floating point number, which is scaled
based on the fractional width.
The data type always needs to be initiated with an integer width and
a fractional width. The integer width specifies how many bits are used
to represent the integer part of the value. The fractional width
specifies how many bits represent the fractional part of the value. As
the value is always considered a signed number, the overall width is
M{width = integer width + fractional width + 1}.
There are different nomenclatures used to specify fixed point
fractional data types. One commonly used one is the s-number
representation. For example s0.9 specifies a signed fixed point number
with 0 bits being used to represent the integer width and 9 bits are
used to represent the fractional width of the number. In this
documentation we use a second type of representation which is
A(0,9). The capital 'A' specifies the number to be a signed number,
with the first number in the parenthesis being the integer bit width and
the second number after the comma being the fractional bit width. Note
that due to the fact that both representations show a signed number,
the overall width of this number is 10 bit.
Fundamental fixed point arithmetic operations
---------------------------------------------
The class follows the fundamental fixed point arithmetic rules as
described in the document "Fixed Point Arithmetic: An Introduction" by
Randy Yates. Availble from this page:
http://www.digitalsignallabs.com/fp.pdf
Basic usage
-----------
This section describes the basic usage of the class. For further
details refer to the respective documentation of member functions.
>>> from deModel import DeFixedInt
>>> a = DeFixedInt(8,2, 2.5)
>>> print a
<10 (2.500) A(8,2)>
>>> b = DeFixedInt(8,2, 3.75)
>>> print b
<15 (3.750) A(8,2)>
>>> c = a + b
>>> print c
<25 (6.250) A(9,2)>
>>> d = a * b
>>> print d
<150 (9.375) A(17,4)>
Here some examples in connection with numpy
>>> from deModel import arrayFixedInt
>>> a = arrayFixedInt(8,2, [4.5, 1.25, 3.75, 2.0])
>>> print a
[<18 (4.500) A(8,2)> <5 (1.250) A(8,2)> <15 (3.750) A(8,2)>
<8 (2.000) A(8,2)>]
>>> b = arrayFixedInt(8,2, [2.25, 3.0, 1.5, 3.75])
>>> print b
[<9 (2.250) A(8,2)> <12 (3.000) A(8,2)> <6 (1.500) A(8,2)>
<15 (3.750) A(8,2)>]
>>> c = a + b
>>> print c
[<27 (6.750) A(9,2)> <17 (4.250) A(9,2)> <21 (5.250) A(9,2)>
<23 (5.750) A(9,2)>]
Internals
---------
The class specifies only a few private variables and to save memory
they are fixed via the __slots__ member variable. There are two
notable effects of this. One is that only assignments to member
variables are allowed that are listed in the __slots__ variable.
Another is that by default no weak reference is supported for an
instance of this class. For further details on this refer to:
http://docs.python.org/ref/slots.html#l2h-218
The stored data are all set as private data and if necessary can be
accessed via properties. For example the actual value is stored in the
variable self.__value and can be accessed via the value property. This
allows for the set property for example to test the data type and in
case of a float value to convert the float to integer, depending on
the specified integer and fractional width.
Integer and fractional width are values that can be specified when
instantiating the class and their values are later read only. This is
due to the fact that they are changed indirect by operations applied
to the actual value of the class.
The class supports the read only property width, which returns the
used bit width. The bit width is integer width + fractional width + 1.
'''
__slots__ = ('__intWidth', '__fractWidth', '__roundMode', '__value')
def __init__(self, intWidth=0, fractWidth=15, value=0, roundMode='round_even'):
'''
@type intWidth : unsigned integer number
@param intWidth : Number of bits used to store the integer part of the
value. As the class stores signed numbers the resulting
bit width is intWidth + fractWidth + 1
@type fractWidth : unsigned integer number
@param fractWidth : Number of bits that are used to store the fractional
part of the value. The fractional width determines
the scaling that is applied to floating point values.
The maximum value allowed is 1 bit smaller than width,
as DeFixedInt is storing signed numbers.
@type value : integer or floating point number
@param value : Assigns the initial value to the data type. If the value
is of integer type the value is just assigned as is. If
the value is of float type the value is scaled up,
depending on the fractWidth value.
@type roundMode : string
@param roundMode : Specifies the way rounding is done for operations
with this data type. The setting affects the rounding
done when converting a floating point value to fixed
point representation
Possible settings:
'trunc' - truncate the result
'round_even' - round the result to the nearest even value
'round' - round the result
'''
# Test for proper parameter
# Setting the value will be tested through the property function
if(intWidth < 0):
raise ValueError( "Integer width needs to be >= 0!")
if(fractWidth < 0):
raise ValueError( "Fractional width needs to be >= 0!")
if( (roundMode != 'trunc') and
(roundMode != 'round_even') and
(roundMode != 'round')):
raise ValueError( "Round mode '%s' not supported!" % roundMode)
self.__intWidth = intWidth
self.__fractWidth = fractWidth
self.__roundMode = roundMode
self._setValue(value)
######################################################################
# properties
######################################################################
def _getValue(self):
'''
Return the value
'''
return self.__value
def _setValue(self, value):
'''
Allow to set the value
@type value : integer, long, or float
@param value : Set the value. An integer or long will be set as is. A
float value will be scaled based on the fractional
width
'''
if(isinstance(value, float)):
#print "float value"
self._fromFloat(value)
elif(isinstance(value, (int, long))):
#print "int value"
self.__value = value
else:
print("unkown type: ", type(value))
self._overflowCheck()
value = property(_getValue, _setValue)
def _getFloatValue(self):
return self._toFloat()
fValue = property(_getFloatValue)
def _getIntWidth(self):
return self.__intWidth
intWidth = property(_getIntWidth)
def _getFractWidth(self):
return self.__fractWidth
fractWidth = property(_getFractWidth)
def _getWidth(self):
'''width property'''
return self.__intWidth + self.__fractWidth + 1
width = property(_getWidth)
def _getRep(self):
'''Return the representation of the fixed point number as string'''
return "A(%d,%d)" % (self.intWidth, self.fractWidth)
rep = property(_getRep)
######################################################################
# overloaded functions
######################################################################
def __copy__(self):
retValue = DeFixedInt(self.intWidth, self.fractWidth, self.value)
return retValue
def __getitem__(self, key):
'''Allow to access a bit or slice of bits
For bit access the respective bit is returned as integer type. For
slicing a DeFixedInt instance is returned with the value set to the
sliced bits and intWidth/fractWidth being adjusted based on the
slice.
When the slice includes the sign bit it is taken over to the return
value. If the sign bit is excluded the bits are taken as is with the
sign bit set to 0.
For example using the 4-bit number -6 = b1010, slicing bits 3:1 -->
b101 includes the sign bit, the result is -3.
Now using the 4-bit number -3 = b1101, slicing bits 2:1 --> b10,
however, the slice excludes the sign bit, hence the result is 2.
The same is true for a positive 4-bit number like 5 = b0101. Slicing
bits 2:1 --> b10. As the sign bit is not included in the slice the
result is again 2. Notice that even though the msb of the slice is 1
the result is not negative.
@type key : Integer or slice
@param key : Index value 0 ... len-1 will return bits lsb ... msb.
Negative numbers -1 ... -len will return the bits
msb ... lsb.
For a slice the bits are specified in the order
[msb:lsb]. With msb > lsb. The msb bit is not included
in the slice. For example, the slice [4:] will return
4 bits, namely bits 3, 2, 1, and 0. The slice [4:2]
will return 4-2=2 bits, namely bits 3 and 2.
@rtype : Integer or DeFixedInt for slice
@return : Bit or slice specified by key
'''
if(isinstance(key, int)):
i = key
if(i >= self.width or i < (-self.width)):
raise IndexError( "list index %d out of range %d ... %d" % \
(i, -self.width, (self.width-1)))
if(i < 0):
shift = self.width + i
else:
shift = i
return ((self.value >> shift) & 0x1)
elif(isinstance(key, slice)):
msb, lsb = key.start, key.stop
# first determine the new value
if(lsb == None):
lsb = 0
if(lsb < 0):
raise ValueError("DeFixedInt[msb:lsb] requires lsb >= 0\n" \
" lsb == %d" % lsb)
if(msb == None or msb == self.width):
if(msb == None):
msb = self.width
newValue = (self.value >> lsb)
else:
newValue = None
if(msb <= lsb):
raise ValueError( "DeFixedInt[msb:lsb] requires msb > lsb\n" \
" [msb:lsb] == [%d:%d]" % (msb, lsb))
if(msb > self.width):
raise ValueError("DeFixedInt[msb:lsb] requires msb <= %d\n" \
" msb == %d" % (self.width, msb))
if(not newValue):
newValue = (self.value & (1 << msb)-1) >> lsb
# then the new intWidth and fractWidth
if(lsb < self.fractWidth):
if(msb > self.fractWidth):
newFractWidth = self.fractWidth - lsb
if(msb > self.intWidth + self.fractWidth):
newIntWidth = self.intWidth
else:
newIntWidth = msb - self.fractWidth
else:
newIntWidth = 0
newFractWidth = msb - lsb
else:
newFractWidth = 0
if(msb > (self.intWidth + self.fractWidth)):
newIntWidth = msb - lsb - 1
else:
newIntWidth = msb - lsb
# create new instance and return it
retValue = DeFixedInt(newIntWidth, newFractWidth, newValue)
return retValue
else:
raise TypeError( "DeFixedInt item/slice index must be integer")
def __repr__(self):
str = "<%d" % (self.__value)
#str += " (%.3f)" % (self.fValue)
str += " A(%d,%d)>" % (self.__intWidth, self.__fractWidth)
return str
def __str__(self):
str = "<%d" % (self.__value)
str += " (%.3f)" % (self.fValue)
str += " A(%d,%d)>" % (self.__intWidth, self.__fractWidth)
return str
def __hex__(self):
'''Return the hex representation of the value.
The number is represented with the minimum number of nibbles as
needed based on the width.
Negative numbers are represented as two's complement.
'''
width = self.width
mask = long(2** width) -1
fStr = '0x%%.%dX'%(int(math.ceil(width / 4)))
return fStr % (self.value & mask)
def __mul__(self, other):
'''Fixed Point multiplication
Fixed point representation is calculated based on:
A(a1, b1) * A(a2, b2) = A(a1+a2+1, b1+b2)
@type other : - DeFixedInt
- int; will be first converted to DeFixedInt based on
operand A intWidth/fractWidth
- float; will be scaled and converted to DeFixedInt based
on intWidth/fractWidth of operand A
@param other : Operand B
@rtype : DeFixedInt
@return : A * B
'''
retValue = DeFixedInt()
if(isinstance(other, DeFixedInt)):
#print "__mult__: other is DeFixedInt"
retValue.__intWidth = self.__intWidth + other.__intWidth + 1
retValue.__fractWidth = self.__fractWidth + other.__fractWidth
retValue.__roundMode = self.__roundMode
retValue.value = self.value * other.value
elif(isinstance(other, (int, long, float))):
#print "__mult__: other is '%s' "% type(other)
b = DeFixedInt(self.__intWidth, self.__fractWidth, other, self.__roundMode)
retValue = self * b
else:
msg = "'%s' not supported as operator for DeFixedInt multiplication"%type(other)
raise TypeError( msg)
return retValue
#def __div__(self, other):
# '''Fixed point division
# Fixed pont representation is calculated based on:
# A(a1, b1) / A(a2, b2) = A(a1+b2+1, a2+b1)
# @type other : - DeFixedInt
# - int; will be first converted to DeFixedInt based on
# operand A intWidth/fractWidth
# - float; will be scaled and converted to DeFixedInt based
# on intWidth/fractWidth of operand A
# @param other : Operand B
# @rtype : DeFixedInt
# @return : A / B
# '''
# retValue = DeFixedInt()
# if(isinstance(other, DeFixedInt)):
# retValue.__intWidth = self.__intWidth + other.fractWidth + 1
# retValue.__fractWidth = self.__fractWidth + other.__intWidth
# retValue.__roundMode = self.__roundMode
# retValue.value = self.value / other.value
# else:
# msg = "'%s' not supported as operator for DeFixedInt division"%type(other)
# raise TypeError, msg
# return retValue
def __add__(self, other):
'''Scale operand b to the representation of operand a and add them
A(a, b) + A(a, b) = A(a+1, b)
@type other : DeFixedInt
@param other : Operand B
@rtype : DeFixedInt
@return : A + B
'''
retValue = DeFixedInt(self.intWidth+1, self.fractWidth)
#print
#print "before change: self: %s \n--> other: %s" %(self, other)
temp = copy.copy(other)
temp.newRep(self.intWidth, self.fractWidth)
#print "after change: self: %s \n--> other: %s"% (self, other)
#print "after change: self: %s \n--> temp: %s"% (self, temp)
retValue.value = self.value + temp.value
return retValue
def __sub__(self, other):
'''Scale operand b to the representation of operand a and subtract them.
A(a, b) - A(a, b) = A(a+1, b)
@type other : DeFixedInt
@param other : Operand B
@rtype : DeFixedInt
@return : A - B
'''
retValue = DeFixedInt(self.intWidth+1, self.fractWidth)
temp = copy.copy(other)
temp.newRep(self.intWidth, self.fractWidth)
retValue.value = self.value - temp.value
return retValue
def __lshift__(self, other):
'''Left shift operation
Shift left the value by the specified amount of bits, without
changing intWidth/fractWidth
@type other : Integer or long
@param other : Number of bits to shift
'''
# check for the other value, only support 'int' type
if(not isinstance(other, (int, long))):
msg = "unsupported operand type(s) for <<: 'DeFixedInt' and '%s'"% type(other)
raise TypeError(msg)
if(other < 0):
raise ValueError("negative shift count")
retValue = DeFixedInt()
width = self.width
retValue.__intWidth = self.intWidth
retValue.__fractWidth = self.fractWidth
retValue.__roundMode = self.__roundMode
retValue.value = self.value << other
return retValue
def __rshift__(self, other):
'''Right shift operation
Shift the value by the specified amount of bits, without changing
intWidth/fractWidth.
The result will be adjusted based on the selected rounding mode.
@type other : integer or long
@param other : Number of bits to shift the value right
'''
if(not isinstance(other, (int, long))):
msg = "unsupported operand type(s) for <<: 'DeFixedInt' and '%s'"% type(other)
raise TypeError(msg)
if(other < 0):
raise ValueError("negative shift count")
retValue = DeFixedInt()
width = self.width
retValue.__intWidth = self.intWidth
retValue.__fractWidth = self.fractWidth
retValue.__roundMode = self.__roundMode
if(other > 0):
if(self.__roundMode == 'round'):
roundBit = self[other-1] # take the msb that would get lost
retValue.value = (self.value >> other) + roundBit # and add it
elif(self.__roundMode == 'round_even'):
newBitZero = self[other]
msbTrunc = self[other-1]
remainTrunc = self[other-1:0]
# TODO: should the 'not' work just for DeFixedInt?
if(msbTrunc and not remainTrunc.value): # truncing 100..-> round even
retValue.value = (self.value >> other) + \
(newBitZero & msbTrunc)
else: # not .500.. case, round normal
retValue.value = (self.value >> other) + msbTrunc
else: # __roundMode == 'trunc'
retValue.value = self.value >> other
else:
retValue = self
return retValue
######################################################################
# private methods
######################################################################
def _fromFloat(self, value):
'''Convert float value to fixed point'''
self.__value = self.round(value * 2.0**self.__fractWidth )
def _toFloat(self):
'''Convert fixed point value to floating point number'''
return (self.__value / (2.0 ** self.__fractWidth))
def _overflowCheck(self):
'''Verify that the set value does not exceed the specified width'''
maxNum = 2 ** (self.width - 1) - 1
minNum = - 2 ** (self.width - 1)
if(self.value > maxNum or self.value < minNum):
msg = "Value: %d exeeds allowed range %d ... %d" % \
(self.value, minNum, maxNum)
raise DeFixedIntOverflowError(msg)
######################################################################
# public methods (interface)
######################################################################
def isOverflowing(self, intWidth, fractWidth):
'''Return True if the stored value exceeds the specified width
This function allows to test whether a value would fit in an
instance with different width.
@type intWidth : integer
@param intWidth : integer width
@type fractWidth : integer
@param fractWidth : fractional width
@rtype : Boolean
@return : True if self.__value is overflowing A(intWidth, fractWidth)
False if self.__value is not overflowing the specified parameters.
'''
maxNum = 2 ** (intWidth + fractWidth) - 1
minNum = - 2 ** (intWidth + fractWidth)
retValue = False
if(self.value > maxNum or self.value < minNum):
retValue = True
return retValue
def newRep(self, intWidth, fractWidth):
'''Change the fixed point representation to the specified representation.
The operation changes the intWidth and fractWidth based on the given
parameter. The value of the instance is changed by this operation,
however the representing floating point number stays the same,
except for rounding issues when reducing the fractional width.
If the number does not fit the new representation a DeFixedIntOverflowError
exception is called.
@type intWidth : integer
@param intWidth : new integer width
@type fractWidth : integer
@param fractWidth : new fractional representation
'''
# first adjust the fractional width
if(fractWidth > self.fractWidth):
n = fractWidth - self.fractWidth
# need to grow first to avoid overflow
self.__fractWidth = fractWidth
self.value = self.value << n
elif(fractWidth < self.fractWidth):
# here we might loose precision
n = self.fractWidth - fractWidth
self.value = self.value >> n
self.__fractWidth = fractWidth
# next adjust the integer width
if(intWidth > self.intWidth):
self.__intWidth = intWidth
elif(intWidth < self.intWidth):
# in case of a smaller intWidth we need to check for possible overflow
if(self.isOverflowing(intWidth, self.fractWidth)):
msg = "New intWidth: %d will overflow current value: %d" %\
(intWidth, self.value)
raise DeFixedIntOverflowError(msg)
self.__intWidth = intWidth
def round(self, value):
'''Return the floating point value as int, rounded depending on the
roundMode setting.
@type value : float
@param value : Value to be rounded based on the set self.__roundMode
@rtype : float
@return : Based on the set self.__roundMode rounded number
'''
if(self.__roundMode == 'trunc'):
retVal = int(value)
elif(self.__roundMode == 'round_even'):
# if value is .50 round to even, if not, round normal
fract, integer = math.modf(value)
absIValue = int(abs(integer))
if(int(integer) < 0):
sign = -1
else:
sign = 1
# TODO: look for a better way to compare here for 0.500
# floating point compare does not seem to be so good
if((abs(fract) - 0.5) == 0.0):
if((absIValue%2) == 0): # even
retVal = absIValue * sign
else: # odd
retVal = (absIValue + 1) * sign
else:
retVal = round(value)
elif(self.__roundMode == 'round'):
retVal = round(value)
else:
raise "ERROR: DeFixedInt.round(): '%s' not supported round mode!" % \
self.__roundMode
return int(retVal)
def showRange(self):
'''
Print out the possible value range of the number.
'''
min = -2**self.intWidth
max = 2**self.intWidth - 1.0 / 2.0**self.fractWidth
print( "A(%d, %d): " %(self.intWidth, self.fractWidth))
print( "%f ... %f" % (min, max))
def showValueRange(self):
'''Print out the integer # and its floating point representation'''
fract = 2**self.fractWidth
min = -2**self.intWidth
for i in range(2**self.width):
print( "i: %d --> %f" %(i, (min+ i/ 2.0**self.fractWidth)))
def bit(self):
'''Return number as bit string'''
pass
######################################################################
#
# main()
#
if __name__ == '__main__':
a = DeFixedInt()
a.value = 1
print( "Showing range:")
a.showRange()
print( "printing a: ", a)
a = DeFixedInt(8, 0, 1)
print("Showing range:")
a.showRange()
print( "printing a: ", a)
a = DeFixedInt(8, 3, 1.2)
print( "Showing range: ")
a.showRange()
print("printig a: ", a)
a = DeFixedInt(8, 2)
print("Representation a: ", a.rep)
b = DeFixedInt(8, 0)
print("Representation b: ", b.rep)
c = a + b
print("Representation c: ", c.rep)
a = 1.25
b = 2.0
c = a + b
print(c)