일출과 일몰


12

나는 로맨틱 한 느낌이 들었습니다. 아내가 우리가있는 곳에서 일출과 일몰을 보러 나가는 것을 좋아합니다. 이 연습을 위해 어떤 날짜, 위도 및 경도에 관계없이 일몰 또는 일출 시간을 알려주는 코드가 없다고 가정 해 봅시다.

코더는 십진수 위도 및 경도 (N 및 W로 표시되므로 S 및 E는 음수로 표시됨) 및 YYYY-MM-DD 형식의 날짜를 사용하는 가능한 가장 작은 코드를 생성해야합니다 (코더). 2000 년 1 월 1 일부터).

예 : 오늘 호주 시드니에서

riseset -33.87 -151.2 2013-12-27

05:45 20:09

보너스 : 고도를 고려할 수있는 경우 -100 일광 절약을 고려할 수있는 경우 -100

코드는 위도 및 경도를 기준으로 또는 클라이언트 시스템의 자체 시간대를 기준으로 입력에 지정된 관련 시간대에서 시간을 내야합니다.


3
잠깐, 우리는 [위도 x 경도] => [시간대] 조회를 수행해야합니까? 이를위한 데이터 파일이 있습니까? 아니면 액세스 할 수있는 서버입니까? 아니면 그런 것들이 내장 된 언어가 있습니까? 어느 것을 말씀해 주시겠습니까? 아니면 시간대 경계를 외워야합니까? 어떤 정밀도로? 이 데이터는 어디서 구할 수 있습니까? 이 데이터가 대부분의 코드 길이를 차지한다는 것을 알고 있습니까? 시간대 경계에 정확히 맞는 좌표는 어떻습니까? 지리 대라고 말해? 또한 입력이 극지 밤 / 낮 동안 극지방 인 경우 어떤 동작이 허용됩니까? 범위를 벗어난 좌표는 어떻습니까?
John Dvorak

나는 것 좋아하는 이상적인 영역 위의 점을 기준으로 수평선을 계산하기 위해 도전,하지만 난 싫어 찾기 위해 관련 도전, 손으로 압축을 프로그래밍 방식 decopmress하고, 시간대 매핑 조회에서 찾아보십시오. 물론 이상적인 시간대를 사용할 수 없다면 (정오 동안 태양이 가장 높고 가장 가까운 시간으로 반올림되도록 오프셋이 선택됨).
John Dvorak

1
@JanDvorak 사용하는 언어가 고객의 시간대를 이용할 수 있다면 반드시 그렇게하십시오.
WallyWest

1
극지방이 낮 / 밤일 때 극지방에 대해 바람직한 행동은 무엇입니까?
John Dvorak

1
다음은 정확히 같은 않는 도구입니다 weatherimages.org/latlonsun.html는
에 이사 아딜

답변:


4

나는 이것을 쓰는 데 꽤 많은 시간을 보냈다.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from math import *


class RiseSet(object):

    __ZENITH = {'official': 90.833,
                'civil': '96',
                'nautical': '102',
                'astronomical': '108'}

    def __init__(self, day, month, year, latitude, longitude, daylight=False,
                 elevation=840, zenith='official'):
        ''' elevation is set to 840 (m) because that is the mean height of land above the sea level '''

        if abs(latitude) > 63.572375290155:
            raise ValueError('Invalid latitude: {0}.'.format(latitude))

        if zenith not in self.__ZENITH:
            raise ValueError('Invalid zenith value, must be one of {0}.'.format
                            (self.__ZENITH.keys()))

        self.day = day
        self.month = month
        self.year = year
        self.latitude = latitude
        self.longitude = longitude
        self.daylight = daylight
        self.elevation = elevation
        self.zenith = zenith

    def getZenith(self):
        return cos(radians(self.__ZENITH[self.zenith]))

    def dayOfTheYear(self):
        n0 = floor(275*self.month/9)
        n1 = floor((self.month + 9) / 12)
        n2 = (1 + floor((self.year - 4*floor(self.year/4) + 2) / 3))
        return n0 - (n1*n2) + self.day - 30

    def approxTime(self):
        sunrise = self.dayOfTheYear() + ((6 - (self.longitude/15.0)) / 24)
        sunset = self.dayOfTheYear() + ((18 - (self.longitude/15.0)) / 24)
        return (sunrise, sunset)

    def sunMeanAnomaly(self):
        sunrise = (0.9856 * self.approxTime()[0]) - 3.289
        sunset = (0.9856 * self.approxTime()[1]) - 3.289
        return (sunrise, sunset)

    def sunTrueLongitude(self):
        sma = self.sunMeanAnomaly()
        sunrise = sma[0] + (1.916*sin(radians(sma[0]))) + \
                  (0.020*sin(radians(2*sma[0]))) + 282.634

        if sunrise < 0:
            sunrise += 360
        if sunrise > 360:
            sunrise -= 360

        sunset = sma[1] + (1.916*sin(radians(sma[1]))) + \
                 (0.020*sin(radians(2*sma[1]))) + 282.634

        if sunset <= 0:
            sunset += 360
        if sunset > 360:
            sunset -= 360

        return (sunrise, sunset)

    def sunRightAscension(self):
        stl = self.sunTrueLongitude()
        sunrise = atan(radians(0.91764*tan(radians(stl[0]))))

        if sunrise <= 0:
            sunrise += 360
        if sunrise > 360:
            sunrise -= 360

        sunset = atan(radians(0.91764*tan(radians(stl[1]))))

        if sunset <= 0:
            sunset += 360
        if sunset > 360:
            sunset -= 360

        sunrise_stl_q = (floor(stl[0]/90)) * 90
        sunrise_ra_q = (floor(sunrise/90)) * 90
        sunrise = sunrise + (sunrise_stl_q - sunrise_ra_q)
        sunrise = sunrise/15.0

        sunset_stl_q = (floor(stl[1]/90)) * 90
        sunset_ra_q = (floor(sunset/90)) * 90
        sunset = sunrise + (sunset_stl_q - sunset_ra_q)
        sunset /= 15.0

        return (sunrise, sunset)

    def sunDeclination(self):
        sunrise_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[0]))
        sunrise_cos_dec = cos(radians(asin(radians(sunrise_sin_dec))))

        sunset_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[1]))
        sunset_cos_dec = cos(radians(asin(radians(sunrise_sin_dec))))

        return (sunrise_sin_dec, sunrise_cos_dec,
                sunset_sin_dec, sunset_cos_dec)

    def sunHourAngle(self):
        sd = self.sunDeclination()
        sunrise_cos_h = (cos(radians(self.getZenith())) - (sd[0]* \
                         sin(radians(self.latitude))) / (sd[1]* \
                         cos(radians(self.latitude))))
        if sunrise_cos_h > 1:
            raise Exception('The sun never rises on this location.')

        sunset_cos_h = (cos(radians(self.getZenith())) - (sd[2]* \
                         sin(radians(self.latitude))) / (sd[3]* \
                         cos(radians(self.latitude))))
        if sunset_cos_h < -1:
            raise Exception('The sun never sets on this location.')

        sunrise = 360 - acos(radians(sunrise_cos_h))
        sunrise /= 15.0

        sunset = acos(radians(sunrise_cos_h))
        sunset /= 15.0

        return (sunrise, sunset)

    def localMeanTime(self):
        sunrise = self.sunHourAngle()[0] + self.sunRightAscension()[0] - \
                 (0.06571*self.approxTime()[0]) - 6.622
        sunset = self.sunHourAngle()[1] + self.sunRightAscension()[1] - \
                 (0.06571*self.approxTime()[1]) - 6.622
        return (sunrise, sunset)

    def convertToUTC(self):
        sunrise = self.localMeanTime()[0] - (self.longitude/15.0)

        if sunrise <= 0:
            sunrise += 24
        if sunrise > 24:
            sunrise -= 24

        sunset = self.localMeanTime()[1] - (self.longitude/15.0)

        if sunset <= 0:
            sunset += 24
        if sunset > 24:
            sunset -= 24

        return (sunrise, sunset)

    def __str__(self):
        return None

이제는 아직 작동하지 않습니다 (일부 계산을 망쳤습니다)-나중에 다시 가져 와서 (여전히 용기가 있다면) 다시 작성하여 주석 처리하십시오 .

또한 주제를 연구하는 동안 찾은 흥미로운 자료도 있습니다.


3
방금 # It's late, I'm tired, and OP is a prick for asking me to do this. 이 작업을 수행 할 의무가 없다는 것에 대한 귀하의 의견을 보았습니다 ... 코드에 이와 같은 의견을 적어주지 마십시오 ... 다른 코더와 나에게 호의적이지 않습니다. 나는 당신이 그것에게 빨간 뜨거운 이동과 당신이 제공 한 다른 링크를 주었다는 사실에 감탄하지만, 이와 같은 의견을 다시는 사용하지 마십시오 ...
WallyWest

@ Eliseod'Annunzio 사과드립니다.
Deneb

@ Eliseod'Annunzio 난 당신을 화나게하지 않았다. 또한 연구와 코딩에 절대적으로 환상적인 아이디어를 제공해 주셔서 감사합니다. 이제 이것을 자립 파이썬 모듈 (sys 인수 등)로 바꾸고 싶습니다. 이전에 생각했던 것보다 조금 더 복잡하다는 것이 밝혀졌지만, 이것을 없애려고합니다. 다시 감사합니다.
Deneb

@Alex, 당신은이 도전이 한 살이라는 것을 알고 있습니까? 나는 그가 이겼을 것이라고 확신한다.
mbomb007

@ mbomb007 : 몰랐어요.
Alex A.
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.