Skip to content

Commit

Permalink
Merge pull request #7 from FileGo/6
Browse files Browse the repository at this point in the history
Fix anomaly where sun does not rise or set (fixes #6).
  • Loading branch information
nathan-osman committed Oct 29, 2020
2 parents 7c449e7 + 7835498 commit 9a83cd1
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -26,4 +26,4 @@ Next, feed the information into the SunriseSunset() method:
2000, time.January, 1, // 2000-01-01
)

The two return values will be the sunrise and sunset times for the location on the given day as time.Time values.
The two return values will be the sunrise and sunset times for the location on the given day as time.Time values. If sun does not rise or set, both return values will be time.Time{}.
12 changes: 12 additions & 0 deletions hourangle.go
Expand Up @@ -13,5 +13,17 @@ func HourAngle(latitude, declination float64) float64 {
numerator = -0.01449 - math.Sin(latitudeRad)*math.Sin(declinationRad)
denominator = math.Cos(latitudeRad) * math.Cos(declinationRad)
)

// Check for no sunrise/sunset
if numerator/denominator > 1 {
// Sun never rises
return math.MaxFloat64
}

if numerator/denominator < -1 {
// Sun never sets
return -1 * math.MaxFloat64
}

return math.Acos(numerator/denominator) / Degree
}
8 changes: 8 additions & 0 deletions sunrise.go
@@ -1,11 +1,13 @@
package sunrise

import (
"math"
"time"
)

// SunriseSunset calculates when the sun will rise and when it will set on the
// given day at the specified location.
// Returns time.Time{} if there sun does not rise or set
func SunriseSunset(latitude, longitude float64, year int, month time.Month, day int) (time.Time, time.Time) {
var (
d = MeanSolarNoon(longitude, year, month, day)
Expand All @@ -19,5 +21,11 @@ func SunriseSunset(latitude, longitude float64, year int, month time.Month, day
sunrise = solarTransit - frac
sunset = solarTransit + frac
)

// Check for no sunrise, no sunset
if hourAngle == math.MaxFloat64 || hourAngle == -1*math.MaxFloat64 {
return time.Time{}, time.Time{}
}

return JulianDayToTime(sunrise), JulianDayToTime(sunset)
}
7 changes: 7 additions & 0 deletions sunrise_test.go
Expand Up @@ -35,6 +35,13 @@ var dataSunriseSunset = []struct {
time.Date(2004, time.April, 1, 5, 13, 40, 0, time.UTC),
time.Date(2004, time.April, 1, 18, 13, 27, 0, time.UTC),
},
// 2020-06-15 - Igloolik, Canada
{
69.3321443, -81.6781126,
2020, time.June, 25,
time.Time{},
time.Time{},
},
}

func TestSunriseSunset(t *testing.T) {
Expand Down

0 comments on commit 9a83cd1

Please sign in to comment.