Prompt Details
Model
Chat - (gpt-5)
Token size
439 ($0.01372 / call)
Example input
[seniority level, e.g. "Senior Software Engineer"]: Senior Software Engineer
[language/framework]: Python 3.11
[issue_description]: Function returns incorrect total when summing a list of prices containing floats.
[code_snippet]: def calculate_total(prices): total = 0 for price in prices: total += price return round(total, 2) print(calculate_total((19.99, 5.50, 3.45)))
Example output
Summary of Issue:
The function incorrectly sums a list of float prices due to floating-point precision errors inherent in Python’s float type. This can cause totals to be slightly off (e.g., 28.94 becoming 28.9399999), leading to inaccurate financial calculations even after round().
Root Cause:
The use of standard floating-point arithmetic (float) in currency calculations introduces binary representation errors. The problem occurs in:
python
Kopiuj
Edytuj
total += price
because adding floats accumulates tiny precision errors, which round() can’t always correct cleanly.
Fixed Code:
python
Kopiuj
Edytuj
from decimal import Decimal, ROUND_HALF_UP
def calculate_total(prices):
total = Decimal('0.00')
for price in prices:
# Convert each price to Decimal using string to avoid float inaccuracy
total += Decimal(str(price))
# Ensure consistent rounding
return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(calculate_total([19.99, 5.50, 3.45])) # 28.94
Why this works:
Using Decimal preserves exact decimal representation for currency and avoids floating-point rounding artifacts. Converting via str(price) prevents float → Decimal conversion from inheriting binary float errors. quantize ensures consistent two-decimal rounding.
If you want, I can also show you a float-based fix using math.fsum that avoids switching to Decimal but is slightly less precise for financial work. Would you like me to add that?
By purchasing this prompt, you agree to our terms of service
GPT-5
This prompt turns the AI into a methodical Senior Software Engineer specialized in debugging. It guides the model through a step-by-step process to identify, reproduce, and fix bugs in any provided code, delivering a clear root cause analysis, a corrected code version, thorough test cases, and prevention tips — ensuring reliable, production-ready solutions instead of vague guesses.
...more
Added over 1 month ago
