473,654 Members | 3,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

long(Decimal) performance

Hello c.l.p.ers :)

Running long(Decimal) is pretty slow, and the conversion is based on
strings. I'm trying to figure out whether there is a good reason for
using strings like in decimal.py (that reason would be bound to bite me
down the road).
This converts Decimal to long and is much faster in my test system
(PIII 650MHz, but was written on a P133 a year ago :)).

def dec2long(number ):
"""
Convert decimal.Decimal to long.

Hopefully faster than C{int(Decimal() )}.
@param number: A C{decimal.Decim al} value
@return: Long from input
"""
if not isinstance(numb er, Decimal):
raise TypeError, "dec2long requires an instance of Decimal"
elif number._is_spec ial:
if number._isnan() :
raise TypeError, "This Decimal is NaN, an ex-Number"
elif number._isinfin ity():
raise OverflowError, "Cannot convert infinity to long"

else:
longstring = str(number)
if "e" in longstring:
longsplit = longstring.spli t("e")
elif "E" in longstring:
longsplit = longstring.spli t("E")
else:
longsplit = [longstring, "0"]
floatexp = long(len(longsp lit[0].split(".")[1]))
ftol = long(Decimal(lo ngsplit[0]) * 10L**floatexp)
longexp = long(int(longsp lit[1]) - floatexp)
result = ftol * 10L**longexp
return result

For the sake of camparison, here's decimal.py __int__:

def __int__(self):
"""Converts self to an int, truncating if necessary."""
[snip: error checking]
if self._exp >= 0:
s = ''.join(map(str , self._int)) + '0'*self._exp
else:
s = ''.join(map(str , self._int))[:self._exp]
if s == '':
s = '0'
sign = '-'*self._sign
return int(sign + s)

Then, some timings:
>example
Decimal("7.2527 148991228101483 99426210E+12378 ")
>%timeit v = dec2long(exampl e)
10 loops, best of 3: 12 ms per loop
>%timeit v = long(example)
10 loops, best of 3: 283 ms per loop
>dec2long(examp le) == long(example)
True

Some anachronisms (like 10L) and very probably mistakes are present in
that old hack, but it makes decimal somewhat more interesting for me.

The answer to this message might be "decimal will be written in C very
soon, so nevermind", but I'd love to hear that in fact the following
function is wrong and there is a good reason long(Decimal) works based
on strings... or that my function is silly but could be corrected.

Thanks in advance and best regards,
Daniel 'ajaksu' Diniz

PS: my use case is Stirling's approximation of the factorial for large
numbers, feel free to criticize that, too ;)

Aug 12 '06 #1
3 2374
Sorry... I'm ashamed to submit such awful code in my first post. Let me
try again...

from decimal import Decimal
def dec2long(number ):
""" Convert decimal.Decimal to long """
longstring = str(number)
if "e" in longstring:
radix, exponent = longstring.spli t("e")
elif "E" in longstring:
radix, exponent = longstring.spli t("E")
else:
radix, exponent = [longstring, "0"]
floatexp = long(len(radix. split(".")[1]))
floatish = Decimal(radix) * 10L**floatexp
ftol = long(floatish)
longexp = long(int(expone nt) - floatexp)
return ftol * 10L**longexp

This one should run by itself, is more readable and... still smells bad
:(
Sorry again.

Aug 12 '06 #2
In article <11************ **********@b28g 2000cwb.googleg roups.com>,
ajaksu <aj****@gmail.c omwrote:
>
Running long(Decimal) is pretty slow, and the conversion is based on
strings. I'm trying to figure out whether there is a good reason for
using strings like in decimal.py (that reason would be bound to bite me
down the road).
I'm not sure why it's coded that, but it's somewhat irrelevant: right
now, work is being done to convert decimal.py to C code, which will
almost certainly be much faster than your code. Generally speaking, you
should not be using Decimal now with any expectation of speed.
--
Aahz (aa**@pythoncra ft.com) <* http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it." --Brian W. Kernighan
Aug 12 '06 #3
Hi Aahz, thanks for the feedback!

Aahz wrote:
I'm not sure why it's coded that, but it's somewhat irrelevant: right
now, work is being done to convert decimal.py to C code, which will
almost certainly be much faster than your code. Generally speaking, you
should not be using Decimal now with any expectation of speed.
Agreed and agreed.

Just to avoid that the buggy (and unreadable) versions above harm
anyone, here's a better attempt:

def dec2long(number ):
""" Convert C{decimal.Decim al} to long """
decimal_string = str(number)
## Split 123.45E10 -radix = 123.45, exponent = 10
if "e" in decimal_string:
radix, exponent = decimal_string. split("e")
elif "E" in decimal_string:
radix, exponent = decimal_string. split("E")
else:
radix, exponent = (decimal_string , 0)
if exponent:
exponent = int(exponent)
if "." in radix:
## radix = 123.45, radix_decimal_p art_len = 2
radix_decimal_p art_len = long(len(radix. split(".")[1]))
## radix = 123.45, radix_as_long = 123.45 * 10**2 = 12345
radix_as_long = long(Decimal(ra dix) *
(10L**radix_dec imal_part_len))
##corrected_exp onent = 10 - 2 = 8
corrected_expon ent = exponent - radix_decimal_p art_len
## return 12345 * 10**8
result = radix_as_long * 10L** corrected_expon ent
else:
radix_as_long = long(radix)
result = radix_as_long * 10L**exponent
else:
if "." in radix:
radix_integer_p art = long(radix.spli t(".")[0])
else:
radix_integer_p art = long(radix)
result = radix_integer_p art
return result
Working from inside decimal.py allows things to work faster, but anyone
wanting speed REALLY shouldn't use Decimal :). Now I'm trying clnum
("Rational and arbitrary precision floating point numbers"):
http://cheeseshop.python.org/pypi/clnum/1.2

Cheers,
Daniel

Aug 12 '06 #4

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

Similar topics

21
4518
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
3596
by: William Payne | last post by:
Hello, I have a variable of type unsigned long. It has a number of bits set (with set I mean they equal one). I need to determine those bits and their position and create new numbers from them. For example, consider this four-bit number: 1100 from this number I want to extract two numbers: 1000 and 100 had the four-bit number been 0101 I would want to extract 100 and 1. How should I do this? I wish I had some code to post but I don't...
4
9722
by: italia | last post by:
I changed the Fieldsize Property from text to Long Integer and Decimal Places = 6. I had decimals in the original field. But after the transfer, the digits after the decimals are gone. Now even after I have change the Fieldsize propert to Decimal with Scale = 2, the digits after the decimal are not seen. For eg. If the text was 16.27. After I changed to long integer, it
687
23319
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't believe that. in pieces of the application where speed really matters you can still use "normal" functions or even static methods which is basically the same. in C there arent the simplest things present like constants, each struct and enum...
3
6125
by: Andres A. | last post by:
I have bunch of unicode characters stored as Decimal is there a easy way of displaying unicode from Decimal numbers or do i have to convert the decimal to hex then display the hex? i ran into a small problem with converting Dec to hex and displaying the hex, because when i do the conversion between Dec and Hex, i dont know how i can add a \u properly to the result for the compiler to properly recognize it as a unicode string and not a...
3
24740
by: Matt | last post by:
Anybody noticed that SQL Server rounds up if the value is half way between two rounded values, but C#'s Decimal.Round(Decimal,Int32) rounds to nearest even number? >From MSDN: "When d is exactly halfway between two rounded values, the result is the rounded value that has an even digit in the far right decimal position. For example, when rounded to two decimals, the value 2.345 becomes 2.34 and the value 2.355 becomes 2.36. This process...
6
35667
by: fctk | last post by:
hello, i'm trying to compile this small program: int main(void) { unsigned long int max; max = 4000000000;
3
2171
by: Daniel | last post by:
I'm writing an application that (among other things) evaluates mathematical expressions. The user enters strings containing literals and names that later get evaluated using the Python interpreter. Here's a short (very simplified) example: >>> from decimal import Decimal >>> names = dict(a=Decimal('3.625'), b=Decimal(2)) >>> expr = '(a + 2.625) / b' # expression entered by end-user >>> eval(expr, names) Traceback (most recent call...
2
1554
by: KioKrofov | last post by:
I am writing code in C to print out various data values from some test I am running. The data results come in ints, long ints, floats and doubles. Most data values are required to be in decimal, but certain data values only make sense if they are printed in hex. The values are all stored as decimal values, and then I just convert them to hex when I print them out: printf("0x%x", myVal); So, what if myVal is stored in my data file as...
0
8372
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
8814
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
8706
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8475
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5621
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();...
0
4149
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4293
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2709
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
2
1592
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.