Position of the sun given time of day, latitude and longitude

前端 未结 6 1153
误落风尘
误落风尘 2020-11-28 02:24

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 02:44

    This is a suggested update to Josh's excellent answer.

    Much of the start of the function is boilerplate code for calculating the number of days since midday on 1st Jan 2000. This is much better dealt with using R's existing date and time function.

    I also think that rather than having six different variables to specify the date and time, it's easier (and more consistent with other R functions) to specify an existing date object or a date strings + format strings.

    Here are two helper functions

    astronomers_almanac_time <- function(x)
    {
      origin <- as.POSIXct("2000-01-01 12:00:00")
      as.numeric(difftime(x, origin, units = "days"))
    }
    
    hour_of_day <- function(x)
    {
      x <- as.POSIXlt(x)
      with(x, hour + min / 60 + sec / 3600)
    }
    

    And the start of the function now simplifies to

    sunPosition <- function(when = Sys.time(), format, lat=46.5, long=6.5) {
    
      twopi <- 2 * pi
      deg2rad <- pi / 180
    
      if(is.character(when)) when <- strptime(when, format)
      time <- astronomers_almanac_time(when)
      hour <- hour_of_day(when)
      #...
    

    The other oddity is in the lines like

    mnlong[mnlong < 0] <- mnlong[mnlong < 0] + 360
    

    Since mnlong has had %% called on its values, they should all be non-negative already, so this line is superfluous.

提交回复
热议问题