floating accuracy - how to avoid inaccuracy in multiplications and divisions in python -


i working python , playing multiplications , divisions can't accuracy want operations. following example may reach point.

let a = 3 , b = 4, euclidean norm (sqrt(a*a + b*b)) 5.0, , divisions work fine, 3/5.0 0.6, , 4/5.0 = 0.8. when want make following 3 * -0.8 + 0.6*4 answer little number not expected zero.

i know problems inherent data type, registers , in general machine limits, think there must way @ least simple computations (like example) made no errors.

you can use fraction accurate answer:

>>> fractions import fraction >>> fraction(-8, 10) * 3 + fraction(6, 10) * 4 fraction(0, 1) 

or use decimal:

>>> decimal import decimal >>> decimal('-0.8') * 3 + decimal('0.6') * 4 decimal('0.0') 

beware of string used in decimals: using normal numbers make decimals use inaccurate value of number.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -