Ice Cream Forecast Check

EasymathAlso known as Mean Squared Error

A beach kiosk uses a small model to guess how many ice creams it will sell each day, so it knows how much stock to order. At the end of the week the owner has two lists: what the model predicted and what actually sold.

She wants one number that says how far off the model was. A miss of 40 cones means melted stock or angry customers, so big misses should count much more than small ones. Training a model means making a number like this smaller, step by step.

Your task

Write forecastError(predicted, actual). For each day, the miss is predicted[i] - actual[i]. Square every miss, then return the average of those squares.

The two lists always have the same length. If both are empty, return 0.

forecastError(predicted: float[], actual: float[]) → float Numbers are accepted within 1e-6.

Examples

Example 1
Input
predicted = [120, 80, 150]
actual = [100, 90, 150]
Output
166.66666666666666
Why

The misses are 120 - 100 = 20, 80 - 90 = -10 and 150 - 150 = 0. Their squares are 400, 100 and 0. The average is 500 / 3 = 166.666…

Example 2
Input
predicted = [50, 70]
actual = [60, 60]
Output
100
Why

The misses are -10 and +10. If you averaged the misses first you would get 0 and think the model was perfect. Squaring each miss first gives 100 and 100, so the answer is 100.

Constraints

  • 0 ≤ predicted.length = actual.length ≤ 10,000
  • -1,000,000 ≤ predicted[i], actual[i] ≤ 1,000,000
  • Answers within 0.000001 of the expected value (or relatively that close) are accepted.
Start with brute force

There is no slow way here: one loop over the days is already the best you can do, because you have to look at every day at least once.

The traps are wrong formulas, not slow ones. Averaging the misses and then squaring lets misses cancel. Using the absolute value gives a different measure (mean absolute error) that does not punish big misses as much. Forgetting to divide gives a total that grows with the number of days, so a long week always looks worse than a short one.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code