This question has been asked before a little over three years ago. There was an answer given, however I\'ve found a glitch in the solution.
Code below is in R. I\'ve
I encountered a slight problem with a data point & Richie Cotton's functions above (in the implementation of Charlie's code)
longitude= 176.0433687000000020361767383292317390441894531250
latitude= -39.173830619999996827118593500927090644836425781250
event_time = as.POSIXct("2013-10-24 12:00:00", format="%Y-%m-%d %H:%M:%S", tz = "UTC")
sunPosition(when=event_time, lat = latitude, long = longitude)
elevation azimuthJ azimuthC
1 -38.92275 180 NaN
Warning message:
In acos((sin(lat) * cos(zenithAngle) - sin(dec))/(cos(lat) * sin(zenithAngle))) : NaNs produced
because in the solarAzimuthRadiansCharlie function there has been floating point excitement around an angle of 180 such that (sin(lat) * cos(zenithAngle) - sin(dec)) / (cos(lat) * sin(zenithAngle)) is the tiniest amount over 1, 1.0000000000000004440892098, which generates a NaN as the input to acos should not be above 1 or below -1.
I suspect there might be similar edge cases for Josh's calculation, where floating point rounding effects cause the input for the asin step to be outside -1:1 but I have not hit them in my particular dataset.
In the half-dozen or so cases I have hit this, the "true" (middle of the day or night) is when the issue occurs so empirically the true value should be 1/-1. For that reason, I would be comfortable fixing that by applying a rounding step within solarAzimuthRadiansJosh and solarAzimuthRadiansCharlie. I'm not sure what the theoretical accuracy of the NOAA algorithm is (the point at which numerical accuracy stops mattering anyway) but rounding to 12 decimal places fixed the data in my data set.