'Why sum of squares is negative? [duplicate]

Let's consider very basic example:

import numpy as np
recon_x = ([int(x) for x in np.linspace(1, 12288, num = 12288)])
recon_x = np.array([recon_x]).reshape(-1, 12288)

x = ([int(x) for x in np.linspace(230, 13000, num = 12288)])
x = np.array([x]).reshape(-1, 12288)

I want to calculate the sum of squared differences between x and recon_x: I want to do this by code:

np.sum((x - recon_x) ** 2)

But it returns wrong result:

-1341621451

which of course is incorrect, since sum of squares cannot be negative. Do you see why it happens?



Solution 1:[1]

This an overflow issue. You can precise the type of the numpy arrays with dtype to be sure to use higher precision number format.

import numpy as np
recon_x = ([int(x) for x in np.linspace(1, 12288, num = 12288)])
recon_x = np.array([recon_x], dtype="float64").reshape(-1, 12288)

x = ([int(x) for x in np.linspace(230, 13000, num = 12288)])
x = np.array([x], dtype="float64").reshape(-1, 12288)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ZiGaelle