Kevin SJ
Kevin SJ

Reputation: 1

Python: Getting decimal library to return the right amount of decimals?

I'm trying to develop a simple program that finds decimal numbers that are equal to the average of their digits. Example 4.5 (4+5=9 / 2)= 4.5

In order to do this I need to take averages that have several decimal points and compare them to a big iterated list of decimal numbers (I'm using a nested loop to do this).

When I use the Decimal library to do simple division, the answer comes out with four decimal points, like I want: 0.2727

But when I try to print the the averages of my loop. (Decimal(i + y + z + q)) / Decimal(4)) the averages only come out to the hundredth decimal point (0.25 0.5 0.75, etc). Why? I've tried converting into str() and int() before passing into Decimal() and it doesn't work.

from decimal import *
getcontext().prec = 4

print(Decimal(3)/Decimal(9))


numbers1to10 = [0,1,2,3,4,5,6,7,8,9]

for i in numbers1to10:
    for y in numbers1to10:
        for z in numbers1to10:
            for q in numbers1to10:
                if: (Decimal(i + y + z + q)) / Decimal(4)) == ((Decimal(i))+ (Decimal(y)/10) + (Decimal(z)/100)+ (Decimal(q)/1000)):
                    print (((Decimal(i))+ (Decimal(y)/10) + (Decimal(z)/100) + (Decimal(q)/1000)))

Upvotes: 0

Views: 624

Answers (2)

wwii
wwii

Reputation: 23773

0.5 is as precise as it can be. If you want to ensure a fixed width during printing, use string formatting

a = decimal.Decimal(2)/decimal.Decimal(4)
print(f'{a:1.4f}')    #Python v3.6+
print('{:1.4f}'.format(a))

>>>
0.5000
0.5000

Formatted String Literals (new in version 3.6)

Upvotes: 1

zdimension
zdimension

Reputation: 1082

Can't say for sure, but those numbers (0.25 0.5 0.75) look quite "round" to me, by that I mean that they are just 1/4, 2/4 and 3/4 and they don't have any other decimals to show. Then it's normal that you only get to the hundredth. 0.5 is 0.5, no need to show 0.5000.

If you really want to show to 4 decimals with additional zeroes at the end, use the format functions.

Example:

print("%.4f" % 0.5)

Displays 0.5000.

Upvotes: 0

Related Questions