kylebarron / suncalc-py

A Python port of suncalc.js for calculating sun position and sunlight phases
MIT License
60 stars 8 forks source link

RuntimeWarning: invalid value encountered in arccos #13

Open juliangilbey opened 1 year ago

juliangilbey commented 1 year ago

This seems a little strange; presumably some calculation is ending up trying to take arccos of a number greater than 1 (or less than -1), which might indicate a more significant issue.

from datetime import datetime
from suncalc import get_times

date = datetime(2023, 5, 24)
lon = 0
lat = 51.5
get_times(date, lon, lat)

Running this (with suncalc 0.1.3 from PyPI) gives:

/<PATH>/suncalc-env/lib/python3.11/site-packages/suncalc/suncalc.py:202: RuntimeWarning: invalid value encountered in arccos
  return acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d)))
CedricSodira commented 1 year ago

Hi !

Got the exact same error today when using these data: lat = 48.862725, lng = 2.287592

Was thinking it was due to float precision, because lat = 48, lng = 2 doesn't log any error but is less precise than with my first data sample.

rteuwens commented 11 months ago
import suncalc

paris = lat, lon = 48.862725, 2.287592
dates = pd.date_range("2022-01-01", "2022-12-31", freq="D")
lons, lats = [lon] * len(dates), [lat] * len(dates)

times = suncalc.get_times(dates, lons, lats)
night = times["night"]

dates[night[night.isna()].index]
>> DatetimeIndex(['2022-06-12', '2022-06-13', '2022-06-14', '2022-06-15',
                  '2022-06-16', '2022-06-17', '2022-06-18', '2022-06-19',
                  '2022-06-20', '2022-06-21', '2022-06-22', '2022-06-23',
                  '2022-06-24', '2022-06-25', '2022-06-26', '2022-06-27',
                  '2022-06-28', '2022-06-29', '2022-06-30'],
                   dtype='datetime64[ns]', freq=None)

Seems to occur near the summer solstice. This coordinate is in Paris, though; nowhere near the polar circle. I.e., there must be a wrong calculation somewhere. Can corroborate @CedricSodira 's comment. Above code works without issues with values lat = 48, lng = 2.

kylebarron commented 11 months ago

A PR is welcome, but I'm not using this package myself. You might want to check in the JS implementation if they do something different or if the same error occurs there