0

In Python, I am adding float numbers.

I have numbers

client_balance = 40360.7416622703
fund_manager_balance = 676.600516394647 
uits= 6.72791159564433

here is my python code

def update_client_balance(self, record):
    if record.client_id.account_name != ACCOUNT_MANAGER_NAME:
        self.client_balance += record.units

def update_manager_balance(self, record):
    if record.client_id.account_name == ACCOUNT_MANAGER_NAME:
        self.fund_manager_balance += record.units

After execution of these functions I have

client_balance = 40360.7416622703
fund_manager_balance = 683.328427990291

Now I want to validate the result of these functions manually

so (client_balance + fund_manager_balance)(before function execution) -uits - (client_balance + fund_manager_balance)(after function execution)

By Value

40360.7416622703 + 676.600516394647 + 6.72791159564433 - (40360.7416622703 + 683.328427990291) = -0.00000000000727595761418343

It should give me Zero value but it's giving me -0.00000000000727595761418343

Please help me how I can solve this?

Shahzad Farukh
  • 317
  • 1
  • 2
  • 17
  • 1
    This is the nature of floating point numbers, that they are not 100% precise and that the order of operations does matter https://en.wikipedia.org/wiki/Floating-point_arithmetic the solution to your problem is 15.1 of the python documentation https://docs.python.org/3/tutorial/floatingpoint.html – Adrian Jałoszewski May 07 '19 at 08:31
  • @AdrianJałoszewski can I have exmaple code? – Shahzad Farukh May 07 '19 at 08:59

1 Answers1

2

If you are expecting absolutely no error in decimals, decimal module is fit for you. Example:

from decimal import Decimal

client_balance = Decimal('40360.7416622703')
fund_manager_balance = Decimal('676.600516394647')
uits= Decimal('6.72791159564433')

new_client = client_balance # no change according to your code.
new_manager = fund_manager_balance + uits
print(new_client)
print(new_manager)
# validate
err = client_balance + fund_manager_balance + uits - (new_client + new_manager)
print(err)

Outputs:

40360.7416622703
683.32842799029133
0E-14

Note: for a constant, input a String to the Decimal, because if you input a float, the error has already occured when recognized as a float and before changed to a Decimal.

RibomBalt
  • 190
  • 8