Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Decimal(2**0.5) doesn't give the number in the predefined accuracy?

I am doing the following inspired by this thread:

>>> from decimal import *
>>> import math
>>> getcontext().prec = 1000
>>> Decimal(2**0.5)
Decimal('1.4142135623730951454746218587388284504413604736328125')
>>> Decimal(math.sqrt(2))
Decimal('1.4142135623730951454746218587388284504413604736328125')
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572735013846230912297024924836055850737212644121497099935831413222665927505592755799950501152782060571470109559971605970274534596862014728517418640889198609552329230484308714321450839762603627995251407989687253396546331808829640620615258352395054745750287759961729835575220337531857011354374603408498847160386899970699004815030544027790316454247823068492936918621580578463111596668713013015618568987237235288509264861249497715421833420428568606014682472077143585487415565706967765372022648544701585880162075847492265722600208558446652145839889394437092659180031138824646815708263010059485870400318648034219489727829064104507263688131373985525611732204024509122770022694112757362728049573810896750401836986836845072579936472906076299694138047565482372899718032680247442062926912485905218100445984215059112024944134172853147810580360337107730918286931471017111168391658172688941975871658215212822951848847')
>>> 2**0.5
1.4142135623730951

Why Decimal(2**0.5) isn't 1000 digits long?

like image 440
0x90 Avatar asked Nov 24 '25 03:11

0x90


1 Answers

The 2 ** 0.5 is being calculated as a float and then converted to a Decimal. Instead, use two Decimals from the start:

>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 100
>>> Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')

It's important that you use '0.5' rather than 0.5 so that Decimal interprets 0.5 on its own without any intermediate loss of precision from 0.5 being converted to a float and then to a Decimal. (As 0.5 is 2 ** -1, there might not be any loss of precision, but it's better to be safe than sorry.)

like image 118
icktoofay Avatar answered Nov 25 '25 15:11

icktoofay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!