Moved calculations to log-space to avoid overrun of the values.