Hayden Ravenscroft Hayden Ravenscroft - 2 months ago 6
Python Question

Correct usage of Decimal objects in this expression

I need to calculate the area of any regular polygon. I acquired this formula from a good ol' google:

(n * l**2) / (4 * math.tan((180/n) * (math.pi/180)))


No matter how I use
decimal.Decimal
with these values I can never get it to work as intended.
n
and
l
are given as floats.

Can someone apply decimal object to this please? When
n
is 4 and
l
is 2, it should return
4
, but currently it returns
4.00000000000000156234
(or something along those lines).

Answer

You need to set the precision for the decimal object. Pi is an infinite decimal number, so the precision won't be a whole number.

You can do

from decimal import *

getcontext().prec = 1

or add to the decimal object by rounding down.

>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')

take from docs