Learn Python Coding
39.1K subscribers
640 photos
31 videos
24 files
400 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Safe rounding of numbers with math.fsum

import math

# Initial list with fractions
values = [0.1] * 10

# 1. Regular summation via sum()
print(f"Standard sum(): {sum(values)}") # 0.9999999999999999

# 2. Exact summation via math.fsum()
print(f"Exact math.fsum(): {math.fsum(values)}") # 1.0

Eliminating errors when calculating arrays

We've already discussed why float in Python loses accuracy and how Decimal deals with this. But what if you need to add a million ordinary real numbers from a database or matrix, and it's not possible to convert everything to heavy Decimal objects due to a performance hit? The math.fsum() function comes to the rescue.

Eliminating accumulated error: When sequentially adding elements via the standard sum(), the microscopic errors of float are rounded at each step and "accumulate" in the loop. The math.fsum() function tracks intermediate accuracy losses and compensates for them during the calculations.

High performance: Since the math module is written in C, this function works several times faster than manually iterating through the array or using alternative data types. You get the speed of basic float calculations with near-perfect accuracy.

Stability in Data Science: This tool is indispensable when working with weights in neural networks, calculating averages of large samples, or processing financial transactions, where speed is important but it's critical not to lose valuable cents and fractions during mass operations.

🐍 #Python #DataScience #Coding #Programming #MathFsum #TechTips

Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A

🚀 Level up your AI & Data Science skills with HelloEncyclo — a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
13 courses live + 40+ coming soon
🎯 One access, lifetime updates
🔑 Use code: PRESALE-BOOK-WAVE-2GFG
👉 https://helloencyclo.com/?ref=HUSSEINSHEIKHO
3