Practical Examples
Scientific Computing Scenarios
Numerical Integration
def numerical_integration(func, a, b, num_steps=1000):
step = (b - a) / num_steps
total = sum(func(a + i * step) * step for i in range(num_steps))
return total
def test_integration_precision():
def square(x): return x ** 2
result = numerical_integration(square, 0, 1)
expected = 1/3
assert math.isclose(result, expected, rel_tol=1e-6), "Integration precision failed"
test_integration_precision()
Financial Calculations
Currency Conversion
def currency_conversion(amount, rate):
converted = amount * rate
return round(converted, 2)
def test_conversion_precision():
usd_amount = 100.00
exchange_rate = 1.23456
converted = currency_conversion(usd_amount, exchange_rate)
print(f"Converted amount: {converted}")
Machine Learning Applications
Gradient Descent Precision
def gradient_descent(initial_value, learning_rate, iterations):
value = initial_value
for _ in range(iterations):
gradient = compute_gradient(value)
value -= learning_rate * gradient
return value
def compute_gradient(x):
return 2 * x ## Simple example gradient
Comparison Strategy Matrix
| Scenario |
Recommended Strategy |
Tolerance Level |
| Scientific Computing |
Relative Difference |
1e-6 to 1e-9 |
| Financial Calculations |
Absolute Difference |
1e-2 to 1e-4 |
| Machine Learning |
Adaptive Tolerance |
Varies |
Error Handling in Float Comparisons
def safe_float_compare(a, b, strategy='relative', tolerance=1e-9):
try:
if strategy == 'relative':
return math.isclose(a, b, rel_tol=tolerance)
elif strategy == 'absolute':
return abs(a - b) < tolerance
else:
raise ValueError("Invalid comparison strategy")
except TypeError:
print("Cannot compare non-numeric types")
return False
Visualization of Comparison Strategies
graph TD
A[Float Comparison] --> B{Comparison Strategy}
B --> |Relative Tolerance| C[Scaled Error Checking]
B --> |Absolute Tolerance| D[Fixed Error Threshold]
B --> |Adaptive| E[Context-Dependent Tolerance]
Benchmarking Float Comparisons
import timeit
def benchmark_comparison_methods():
relative_method = '''
math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)
'''
absolute_method = '''
abs(0.1 + 0.2 - 0.3) < 1e-9
'''
relative_time = timeit.timeit(relative_method, number=100000)
absolute_time = timeit.timeit(absolute_method, number=100000)
print(f"Relative Method Time: {relative_time}")
print(f"Absolute Method Time: {absolute_time}")
benchmark_comparison_methods()
Key Takeaways for LabEx Developers
- Choose comparison strategy based on context
- Use built-in methods when possible
- Always consider numerical precision
- Test and validate float comparisons