use logaddexp to avoid overflows