1

I am working on a program that needs a high level of accuracy. Unfortunately when I run a simple code such as this:

65.2805151+66.5374849

the result is 131.81799999999998

Instead of a 131.818

How can I go about addressing this issue?

Anubhav
  • 383
  • 2
  • 8
  • what type are you using for your variables? int, float... etc. – Stanley Sep 30 '19 at 23:20
  • The input value could be either an int or a float - so I am defaulting to float in order to get a more accurate result – Anubhav Sep 30 '19 at 23:21
  • 2
    If you need to need high accuracy you should not be using float, but rather double or decimal, take a look at this: http://net-informations.com/q/faq/float.html , tell me if you get it to work :) – Stanley Sep 30 '19 at 23:23
  • 1
    @Stanley I believe Python's floats have double precision – Kei Sep 30 '19 at 23:24
  • @Kei Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit. Double precision (double) gives you 52 bits of significand from: https://stackoverflow.com/a/5098598/3712531 – Stanley Sep 30 '19 at 23:26
  • @Stanley the question has the Python tag. According to the [Python docs](https://docs.python.org/3/library/stdtypes.html) `There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating point numbers are usually implemented using double in C` Python doesn't have a separate type for floats and doubles. What is referred to as a "float" in Python is usually a double. – Kei Sep 30 '19 at 23:31
  • @Kei Ahhh, my bad, thanks for giving me a heads up! I will stay on the lookout for that next time. And happy to learn something new, thanks again Kei – Stanley Sep 30 '19 at 23:32
  • @Stanley. Thank you. Got it to work by converting all the inputs into Decimal. – Anubhav Sep 30 '19 at 23:32
  • @Anubhav That is great! – Stanley Sep 30 '19 at 23:33

1 Answers1

0

You can work mpmath which is a high precision package. Here's the link to its site

import mpmath as mp
a = 65.2805151
b = 66.5374849
mp.dps = 50
summation = [a,b]
print(mp.fsum(summation))

Output:

131.818
Celius Stingher
  • 11,967
  • 4
  • 12
  • 37