프로그램 1.3.5 조화급수 (harmponic.py)
import sys import stdio n = int(sys.argv[1]) total = 0.0 for i in range(1, n+1): # i번째 항목을 합계에 더한다. total += 1.0 / i stdio.writeln(total)
n i total |
합계를 구할 항목 수 루프 제어 변수 구해진 합계 |
이 프로그램은 명령 줄 인수로 정수 n
을 받아 n
번째 조화급수를 출력한다. 수학적 분석을 통해 큰 n
의 경우 대략 ln(n) + 0.57721의 값을 가진다고 알려져 있다. ln(10,000)은 대략 9.21034 정도 된다.
% python3 harmonic.py 2 1.5 % python3 harmonic.py 10 2.9289682539682538 % python3 harmonic.py 10000 9.787606036044348