PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] Why does Python transform exact decimals to approximations in calculations?

 August 07, 2022     decimal, floating-point, python, python-3.x     No comments   

Issue

I wrote this function to avoir typing on a calculator and make my homework faster but something very strange happened :

def G(x):
  return 1 - x ** 2 - (1-x) ** 2

G(1/5) gives 0.31999999999999984

But it is clearly 25/25 - 1/25 - 16/25 with is 8/25 = 0.32


Solution

You can use the decimal module as a workaround.

The decimal module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype.

from decimal import Decimal;

print(float(G(Decimal(1)/Decimal(5))))
0.32


Answered By - Corralien
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing