I need to create a function (in C++) to calculate the sunrise and sunset times, but I am not a mathematician and I cannot find a correct (and easy) way to do that.
I need to get the same results as can be found in:
https://www.esrl.noaa.gov/gmd/grad/solcalc/ and http://sunrise-sunset.org/api
I tried to implement a function based on these articles https://en.wikipedia.org/wiki/Sunrise_equation and http://www.wikihow.com/Estimate-the-Time-of-Sunrise-or-Sunset but the results are wrong. (maybe I am doing something wrong)
Does anyone know a correct (and easy) formula to calculate it? Maybe the formula used by the websites that I mentioned.
Note: values that I have as input: latitude, longitude, date and UTC offset. (I don't have the altitude)
Thanks
Update:
I developed a new function on Matlab that seems to be more accurate but I still not get the exact sunrise and sunset times:
% Parameters definition
lat = -23.545570; % Latitude
lng = -46.704082; % Longitude
UTCoff = -3; % UTC offset
nDays = daysact('01-jan-2017', '15-mar-2017'); % Number of days since 01/01
% Longitudinal correction
longCorr = 4*(lng - 15*UTCoff);
B = 360*(nDays - 81)/365; % I have no idea
% Equation of Time Correction
EoTCorr = 9.87*sind(2*B) - 7.53*cosd(B) - 1.5*sind(B);
% Solar correction
solarCorr = longCorr - EoTCorr;
% Solar declination
delta = asind(sind(23.45)*sind(360*(nDays - 81)/365));
sunrise = 12 - acosd(-tand(lat)*tand(delta))/15 - solarCorr/60;
sunset = 12 + acosd(-tand(lat)*tand(delta))/15 - solarCorr/60;
sprintf('%2.0f:%2.0f:%2.0f\n', degrees2dms(sunrise))
sprintf('%2.0f:%2.0f:%2.0f\n', degrees2dms(sunset))
This function gives me the sunrise at 05:51:25 when it should be 06:09 and the sunset as 18:02:21 when it should be 18:22, according to ESRL (NOAA).
The function was developed based on this: https://www.mathworks.com/matlabcentral/fileexchange/55509-sunrise-sunset/content/SunriseSunset.mlx
Any idea what can I do to improve the accuracy?
As @Richard already answered here, I was mixing things.
In the glossary to the NOAA website, it is written:
So this is exactly the effect that is causing the 'calculation error'.
@Richard have reverse engineered the functions from the Excel sheet provided on NOAA's website and created a Matlab function to calculate it:
Edit: Richard's uploaded an extended version on Matlab File Exchange
See the complete discussion here.
Now, I can use this Matlab function to convert it to a C++ function.