Practice: rainfall fit

curve_fit, plot, and write report.txt.

Fit millimetres vs month index, plot, write report.txt.

Goal

Print a, b and the report.

from pathlib import Path
from scipy.optimize import curve_fit
month = np.array([1.0, 2, 3, 4])
mm = np.array([80.0, 60, 110, 90])  # Nairobi
def f(x, a, b):
    return a * x + b
popt, _ = curve_fit(f, month, mm)
print('a, b', popt.round(3))
plt.scatter(month, mm)
plt.plot(month, f(month, *popt))
plt.xlabel('month')
plt.ylabel('mm')
plt.title('Nairobi rainfall')
plt.savefig('fit.png', dpi=120, bbox_inches='tight')
plt.show()
Path('report.txt').write_text(f'a={popt[0]:.3f} b={popt[1]:.3f}\n', encoding='utf-8')
print(Path('report.txt').read_text(encoding='utf-8'))