extend methods of decimal module
Mark H. Harris
harrismh777 at gmail.com
Thu Feb 27 16:42:37 CET 2014
On Thursday, February 27, 2014 8:42:55 AM UTC-6, Oscar Benjamin wrote:
>
> Some points:
Thanks so much... you have clarified some things I was struggling with...
> 1) Why have you committed the code as a .tar.gz file?
um, to save space... well, I know its tiny, but its just a habit I have... 5kb instead of 25kb...
> 2) This function is not such a good idea:
>
> def D(numform):
> return Decimal(str(numform))
The reason for this is not for strings, but for float literals. All of my functions may take a float literal and things still work, because the D(float) function converts the float literal to a string, which is then passed to the Decimal constructor. so... this works sqrt(0.1) or, sqrt(2.01) Without the D() function float literals may not be passed to the Decimal because it really cannot handle them... 0.1 and others cause it a fit... is there another way to do what I'm looking for here..?
> 3) In many places you've written code like this:
>
> prec=dscale(getcontext().prec +7)
> sqr = (D(x).sqrt()).__round__(prec)
> retscale=dscale(prec)
> The preferred way is:
> with localcontext() as ctx:
> ctx.prec += 7
> sqr = round(D(x).sqrt(), prec)
Thanks...
> i.e. use a context manager to restore the context even if an error
> occurs and use the round builtin rather than the dunder method.
This has confused me, because when I look into the module help text I don't see roun() all I see is
__round__(...) how do I know when the round() method exists vs. __round__(...) ??
> 4) You shouldn't be using round/__round__ for precision rounding: it
> uses decimal places rather than significant figures. If you want to
> round to context precision just use unary +. i.e.:
> return +sqr
whoohoo! thank you.
> 5) The Decimal.sqrt method already rounds to context precision.
> There's no need to compute in higher precision and then round it
> yourself (in fact you're invalidating the correctness of the rounding
> by double-rounding like this). So really it's just:
> def sqrt(x):
> return Decimal(x).sqrt()
ok...
>
> 6) You should organise it in such a way that you're not progressively
> increasing the precision each time one function calls another.
right... well, and if you look at the calls to my __atan__ funcs I am assuming that they are still in the context of the calling func atan().... right...? so no need to even have the bump up in prec there.
>
> Oscar
thanks Oscar, I really appreciate your comments
marcus
More information about the Python-list
mailing list