Created
October 3, 2024 07:30
-
-
Save Xevion/f0a6344e0a460a0e673945b4daef613d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
def approximate_memorized(fahrenheit) -> float: | |
# Nearest memorized temperature | |
close = round((fahrenheit - 5) / 9) * 9 + 5 | |
# Convert to Celsius | |
rough = (close - 32) // 9 | |
# Half of the difference | |
diff = (fahrenheit - close) / 2 | |
return rough + diff | |
def approximate_simple(fahrenheit: float) -> float: | |
return fahrenheit / 2 | |
def exact(fahrenheit: float) -> float: | |
return (fahrenheit - 32) * (5 / 9) | |
def main(): | |
fahrenheit_values = range(0, 5000) | |
memorized_values = list(map(approximate_memorized, fahrenheit_values)) | |
simple_values = list(map(approximate_simple, fahrenheit_values)) | |
exact_values = list(map(exact, fahrenheit_values)) | |
sns.set_theme('notebook') | |
# Plot the approximations | |
plt.figure(1) | |
sns.lineplot(x=fahrenheit_values, y=memorized_values, label='Memorized Approximation') | |
sns.lineplot(x=fahrenheit_values, y=simple_values, label='Simple Approximation') | |
sns.lineplot(x=fahrenheit_values, y=exact_values, label='Exact Conversion') | |
plt.xlabel('Fahrenheit') | |
plt.ylabel('Celsius') | |
plt.title('Temperature Conversion Approximations') | |
plt.legend() | |
plt.show() | |
# Calculate errors | |
memorized_errors = [abs(m - e) / abs(e) if e != 0 else 0 for m, e in zip(memorized_values, exact_values)] | |
simple_errors = [abs(s - e) / abs(e) if e != 0 else 0 for s, e in zip(simple_values, exact_values)] | |
# Plot the errors as a percentage | |
plt.figure(2) | |
sns.lineplot(x=fahrenheit_values, y=memorized_errors, label='Memorized Approximation Error (%)') | |
sns.lineplot(x=fahrenheit_values, y=simple_errors, label='Simple Approximation Error (%)') | |
plt.ylim(bottom=0, top=2) | |
plt.xlabel('Fahrenheit') | |
plt.ylabel('Error (%)') | |
plt.title('Error in Temperature Conversion Approximations') | |
plt.legend() | |
plt.show() | |
f = 0 | |
while f < 100: | |
memorized_error = abs(approximate_memorized(f) - exact(f)) | |
simple_error = abs(approximate_simple(f) - exact(f)) | |
if simple_error < memorized_error: | |
print(f"{f:.5f}F | Simple Error = {simple_error:.4f}, Memorized Error = {memorized_error:.4f}") | |
break | |
f += 0.0001 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment