473,785 Members | 2,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Alternative to Decimal type

Hi all

I have a standard requirement for a 'decimal' type, to instantiate and
manipulate numeric data that is stored in a database. I came up with a
solution long before the introduction of the Decimal type, which has
been working well for me. I know the 'scale' (number of decimal
places) of the number in advance. When I read the number in from the
database I scale it up to an integer. When I write it back I scale it
down again. All arithmetic is done using integers, so I do not lose
accuracy.

There is one inconvenience with this approach. For example, if I have
a product quantity with a scale of 4, and a price with a scale of 2,
and I want to multiply them to get a value with a scale of 2, I have
to remember to scale the result down by 4. This is a minor chore, and
errors are quickly picked up by testing, but it does make the code a
bit messy, so it would be nice to find a solution.

I am now doing some refactoring, and decided to take a look at the
Decimal type. My initial impressions are that it is quite awkward to
use, that I do not need its advanced features, and that it does not
help solve the one problem I have mentioned above.

I therefore spent a bit of time experimenting with a Number type that
suits my particular requirements. I have come up with something that
seems to work, which I show below.

I have two questions.

1. Are there any obvious problems in what I have done?

2. Am I reinventing the wheel unnecessarily? i.e. can I do the
equivalent quite easily using the Decimal type?

--------------------
from __future__ import division

class Number(object):
def __init__(self,v alue,scale):
self.factor = 10.0**scale
if isinstance(valu e,Number):
value = value.value / value.factor
self.value = long(round(valu e * self.factor))
self.scale = scale

def __add__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)+ot her,self.scale)

def __sub__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)-other,self.scal e)

def __mul__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)*ot her,self.scale)

def __truediv__(sel f,other):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)/other,self.scal e)

def __radd__(self,o ther):
return self.__add__(ot her)

def __rsub__(self,o ther):
return Number(other-(self.value/self.factor),se lf.scale)

def __rmul__(self,o ther):
return self.__mul__(ot her)

def __rtruediv__(se lf,other):
return Number(other/(self.value/self.factor),se lf.scale)

def __cmp__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
this = self.value / self.factor
if this < other:
return -1
elif this other:
return 1
else:
return 0

def __str__(self):
s = str(self.value)
if s[0] == '-':
minus = '-'
s = s[1:].zfill(self.sca le+1)
else:
minus = ''
s = s.zfill(self.sc ale+1)
return '%s%s.%s' % (minus, s[:-self.scale], s[-self.scale:])
--------------------

Example usage -
>>>qty = Number(12.5,4)
price = Number(123.45,2 )
>>>print price * qty
1543.13 [scale is taken from left-hand operand]
>>>print qty * price
1543.1250 [scale is taken from left-hand operand]
>>>print Number(qty * price,2)
1543.13 [scale is taken from Number instance]
--------------------

At this stage I have not built in any rounding options, but this can
be done later if I find that I need it.

Any comments will be welcome.

Thanks

Frank Millman
Jun 27 '08 #1
12 2172
On Jun 9, 5:11*pm, Frank Millman <fr...@chagford .comwrote:
I have a standard requirement for a 'decimal' type, to instantiate and
manipulate numeric data that is stored in a database. I came up with a
solution long before the introduction of the Decimal type, which has
been working well for me. I know the 'scale' (number of decimal
places) of the number in advance. When I read the number in from the
database I scale it up to an integer. When I write it back I scale it
down again. All arithmetic is done using integers, so I do not lose
accuracy.

There is one inconvenience with this approach. For example, if I have
a product quantity with a scale of 4, and a price with a scale of 2,
and I want to multiply them to get a value with a scale of 2, I have
to remember to scale the result down by 4. This is a minor chore, and
errors are quickly picked up by testing, but it does make the code a
bit messy, so it would be nice to find a solution.

I am now doing some refactoring, and decided to take a look at the
Decimal type. My initial impressions are that it is quite awkward to
use, that I do not need its advanced features, and that it does not
help solve the one problem I have mentioned above.

I therefore spent a bit of time experimenting with a Number type that
suits my particular requirements. I have come up with something that
seems to work, which I show below.

I have two questions.

1. Are there any obvious problems in what I have done?

2. Am I reinventing the wheel unnecessarily? i.e. can I do the
equivalent quite easily using the Decimal type?
Hi Frank,
I don't know why you think Decimal is complicated: it has some
advanced features, but for what you seem to be doing it should be easy
to replace your 'Number' with it. In fact, it makes things simpler
since you don't have to worry about 'scale'.

Your examples convert easily:

from decimal import Decimal
qty = Decimal('12.5')
price = Decimal('123.45 ')

print price * qty
print qty * price
print (qty * price).quantize (Decimal('0.01' ))

--
Paul Hankin
Jun 27 '08 #2
On Jun 9, 10:54*am, Paul Hankin <paul.han...@gm ail.comwrote:
>
Hi Frank,
I don't know why you think Decimal is complicated: it has some
advanced features, but for what you seem to be doing it should be easy
to replace your 'Number' with it. In fact, it makes things simpler
since you don't have to worry about 'scale'.

Your examples convert easily:

from decimal import Decimal
qty = Decimal('12.5')
price = Decimal('123.45 ')

print price * qty
print qty * price
print (qty * price).quantize (Decimal('0.01' ))
I thought I might be missing something obvious. This does indeed look
easy. Thanks, Paul

Frank
Jun 27 '08 #3
On Jun 9, 4:06*pm, Frank Millman <fr...@chagford .comwrote:
>
Thanks for the reply, Mel. I don't quite understand what you mean.
As so often happens, after I sent my reply I re-read your post and I
think I understand what you are getting at.

One problem with my approach is that I am truncating the result down
to the desired scale factor every time I create a new instance. This
could result in a loss of precision if I chain a series of instances
together in a calculation. I think that what you are suggesting avoids
this problem.

I will read your message again carefully. I think it will lead to a
rethink of my approach.

Thanks again

Frank

P.S. Despite my earlier reply to Paul, I have not abandoned the idea
of using my Number class as opposed to the standard Decimal class.

I did a simple test of creating two instances and adding them
together, using both methods, and timing them. Decimal came out 6
times slower than Number.

Is that important? Don't know, but it might be.
Jun 27 '08 #4
Frank Millman wrote:
On Jun 9, 4:06Â*pm, Frank Millman <fr...@chagford .comwrote:
>>
Thanks for the reply, Mel. I don't quite understand what you mean.

As so often happens, after I sent my reply I re-read your post and I
think I understand what you are getting at.

One problem with my approach is that I am truncating the result down
to the desired scale factor every time I create a new instance. This
could result in a loss of precision if I chain a series of instances
together in a calculation. I think that what you are suggesting avoids
this problem.

I will read your message again carefully. I think it will lead to a
rethink of my approach.

Thanks again

Frank

P.S. Despite my earlier reply to Paul, I have not abandoned the idea
of using my Number class as opposed to the standard Decimal class.

I did a simple test of creating two instances and adding them
together, using both methods, and timing them. Decimal came out 6
times slower than Number.

Is that important? Don't know, but it might be.
It is because it uses arbitrary precision integer literals instead of ieee
floats. It pays this price so you get decimal rounding errors instead of
binary. Yet rounding errors you get...

If you are in money calculations with your Number-class - you certainly want
Decimal instead.

If all you want is auto-rounding... then you might not care.

Diez
Jun 27 '08 #5
Thanks to all for the various replies. They have all helped me to
refine my ideas on the subject. These are my latest thoughts.

Firstly, the Decimal type exists, it clearly works well, it is written
by people much cleverer than me, so I would need a good reason not to
use it. Speed could be a good reason, provided I am sure that any
alternative is 100% accurate for my purposes.

My approach is based on expressing a decimal number as a combination
of an integer and a scale, where scale means the number of digits to
the right of the decimal point.

Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale
1, -123.456 is integer -123456 with scale 3. I am pretty sure that any
decimal number can be accurately represented in this form.

All arithmetic is carried out using integer arithmetic, so although
there may be rounding differences, there will not be the spurious
differences thrown up by trying to use floats for decimal arithmetic.

I use a class called Number, with two attributes - an integer and a
scale. My first attempt required these two to be provided every time
an instance was created. Then I realised that this would cause loss of
precision if I chain a series of instances together in a calculation.
The constructor can now accept any of the following forms -

1. A digit (either integer or float) and a scale. It uses the scale
factor to round up the digit to the appropriate integer.

2. Another Number instance. It takes the integer and scale from the
other instance.

3. An integer, with no scale. It uses the integer, and assume a scale
of zero.

4. A float in string format (e.g. '1.1') with no scale. It uses the
number of digits to the right as the scale, and scales the number up
to the appropriate integer.

For addition, subtraction, multiplication and division, the 'other'
number can be any of 2, 3, or 4 above. The result is a new Number
instance. The scale of the new instance is based on the following rule
-

For addition and subtraction, the new scale is the greater of the two
scales on the left and right hand sides.

For multiplication, the new scale is the sum of the two scales on the
left and right hand sides.

For division, I could not think of an appropriate rule, so I just hard-
coded a scale of 9. I am sure this will give sufficient precision for
any calculation I am likely to encounter.

My Number class is now a bit more complicated than before, so the
performance is not as great, but I am still getting a four-fold
improvement over the Decimal type, so I will continue running with my
version for now.

My main concern is that my approach may be naive, and that I will run
into situations that I have not catered for, resulting in errors. If
this is the case, I will drop this like a hot potato and stick to the
Decimal type. Can anyone point out any pitfalls I might be unaware of?

I will be happy to show the code for the new Number class if anyone is
interested.

Thanks

Frank
Jun 27 '08 #6
Frank Millman wrote:
Thanks to all for the various replies. They have all helped me to
refine my ideas on the subject. These are my latest thoughts.

Firstly, the Decimal type exists, it clearly works well, it is written
by people much cleverer than me, so I would need a good reason not to
use it. Speed could be a good reason, provided I am sure that any
alternative is 100% accurate for my purposes.
[snip]
For addition, subtraction, multiplication and division, the 'other'
number can be any of 2, 3, or 4 above. The result is a new Number
instance. The scale of the new instance is based on the following rule

For addition and subtraction . . .
For multiplication . . .
For division . . .
Out of curiosity, what is the purpose of these numbers? Do they
represent money, measurements, or something else? The reason I ask is
way back in physics class (or maybe chemistry... it was way back :) I
was introduced to the idea of significant digits -- that idea being that
a measured number is only accurate to a certain degree, and calculations
using that number therefore could not be more accurate. Sort of like a
built-in error range.

I'm thinking of developing the class in the direction of maintaining the
significant digits through calculations... mostly as I think it would be
fun, and it also seems like a good test case to get me in the habit of
unit testing. I'll call it something besides Number, though. :)

Is anybody aware of such a class already in existence?
--
Ethan
Jun 27 '08 #7
On Jun 11, 4:39*pm, Ethan Furman <et...@stonelea f.uswrote:
Frank Millman wrote:
Thanks to all for the various replies. They have all helped me to
refine my ideas on the subject. These are my latest thoughts.
Out of curiosity, what is the purpose of these numbers? *Do they
represent money, measurements, or something else?
I am writing a business/accounting application. The numbers represent
mostly, but not exclusively, money.

Examples -

Multiply a selling price (scale 2) by a product quantity (scale 4) to
get an invoice value (scale 2), rounded half-up.

Multiply an invoice value (scale 2) by a tax rate (scale 2) to get a
tax value (scale 2), rounded down.

Divide a currency value (scale 2) by an exchange rate (scale 6) to get
a value in a different currency (scale 2).

Divide a product quantity (scale 4) by a pack size (scale 2) to get an
equivalent quantity in a different pack size.

In my experience, the most important thing is to be consistent when
rounding. If you leave the rounding until the presentation stage, you
can end up with an invoice value plus a tax amount differing from the
invoice total by +/- 0.01. Therefore I always round a result to the
required scale before 'freezing' it, whether in a database or just in
an object instance.

Frank
Jun 27 '08 #8
Frank Millman <fr***@chagford .comwrote:
Thanks to all for the various replies. They have all helped me to
refine my ideas on the subject. These are my latest thoughts.

Firstly, the Decimal type exists, it clearly works well, it is written
by people much cleverer than me, so I would need a good reason not to
use it. Speed could be a good reason, provided I am sure that any
alternative is 100% accurate for my purposes.

My approach is based on expressing a decimal number as a combination
of an integer and a scale, where scale means the number of digits to
the right of the decimal point.

Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale
1, -123.456 is integer -123456 with scale 3. I am pretty sure that any
decimal number can be accurately represented in this form.

All arithmetic is carried out using integer arithmetic, so although
there may be rounding differences, there will not be the spurious
differences thrown up by trying to use floats for decimal
arithmetic.
I used an identical scheme in a product some time ago (written in C
not python). It was useful because it modelled the problem domain
exactly.

You might want to investigate the rational class in gmpy which might
satisfy your requirement for exact arithmetic :-
>>import gmpy
gmpy.mpq(123, 1000)
mpq(123,1000)
>>a = gmpy.mpq(123,10 00)
b = gmpy.mpq(12,100 )
a+b
mpq(243,1000)
>>a*b
mpq(369,25000)
>>a/b
mpq(41,40)
>>>
It is also *very* fast being written in C.

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #9

"Frank Millman" <fr***@chagford .comwrote in message
news:f7******** *************** ***********@25g 2000hsx.googleg roups.com...
| Thanks to all for the various replies. They have all helped me to
| refine my ideas on the subject. These are my latest thoughts.
|
| Firstly, the Decimal type exists, it clearly works well, it is written
| by people much cleverer than me, so I would need a good reason not to
| use it. Speed could be a good reason, provided I am sure that any
| alternative is 100% accurate for my purposes.

The Decimal module is a Python (now C coded in 2.6/3.0, I believe)
implementation of a particular IBM-sponsored standard. The standard is
mostly good, but it is somewhat large with lots of options (such as
rounding modes) and a bit of garbage (the new 'logical' operations, for
instance) added by IBM for proprietary purposes. Fortunately, one can
ignore the latter once you recognize them for what they are.

As Nick indicated, it is not the first in its general category. And I
believe the Decimal implementation could have been done differently.

By writing you own class, you get just what you need with the behavior you
want. I think just as important is the understanding of many of the issues
involved, even if you eventually switch to something else. That is a
pretty good reason in itself.

tjr



Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
4536
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
7
2031
by: Blake T. Garretson | last post by:
I'm having some issues with decimal.Decimal objects playing nice with custom data types. I have my own matrix and rational classes which implement __add__ and __radd__. They know what to do with Decimal objects and react appropriately. The problem is that they only work with Decimals if the custom type is on the left (and therefore __add__ gets called), but NOT if the Decimal is on the left. The Decimal immediately throws the usual...
17
6153
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number. "Decimal Number" sometimes serves to distinguish Base 10 numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal Number" serves to differentiate a number from an integer. For the rest of this post I shall only use either...
6
30032
by: Gilgamesh | last post by:
Is decimal type a good choice to use for storing currency? I've got a situation that when I store 8.50 in a decimal type variable and read it back, I'm getting 8.5. Is there a better data type to store currency? Thanks, Gilgamesh
43
6898
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's another story.) The data is written once and then read many times. Each primitive read requires unboxing. The data reads are critical to overall app performance. In the hopes of improving performance, we have tried to find a way to avoid the...
15
12825
by: Kay Schluehr | last post by:
I wonder why this expression works: >>> decimal.Decimal("5.5")**1024 Decimal("1.353299876254915295189966576E+758") but this one causes an error 5.5**1024 Traceback (most recent call last):
8
9561
by: Gilbert Fine | last post by:
This is a very strange exception raised from somewhere in our program. I have no idea how this happen. And don't know how to reproduce. It just occurs from time to time. Can anyone give me some suggestion to fix this? Thanks. -- Gilbert
25
3037
by: Lennart Benschop | last post by:
Python has had the Decimal data type for some time now. The Decimal data type is ideal for financial calculations. Using this data type would be more intuitive to computer novices than float as its rounding behaviour matches more closely what humans expect. More to the point: 0.1 and 0.01 are exact in Decimal and not exact in float. Unfortunately it is not very easy to access the Decimal data type. To obtain the decimal number 12.34 one...
0
28071
Frinavale
by: Frinavale | last post by:
Convert a Hex number into a decimal number and a decimal number to Hex number This is a very simple script that converts decimal numbers into hex values and hex values into decimal numbers. The example following this one demonstrates how to convert decimal numbers into binary values. A hex number is a string that contains numbers between 0-9 and characters A-F; where A = 10, B = 11, ..., F = 15. (For more information please look up...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9481
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10341
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9954
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8979
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.