📜  查找第N个谐波数的程序(1)

📅  最后修改于: 2023-12-03 14:55:35.501000             🧑  作者: Mango

Program to Find the N-th Harmonic Number

In harmonic analysis, a harmonic is a component frequency of a complex waveform, typically a sine wave. A harmonic frequency is a multiple of a fundamental frequency, also known as the first harmonic. In music, each whole number multiple of the fundamental frequency is considered a harmonic.

In this program, we will find the N-th harmonic number, which is the reciprocal of the sum of the first N natural numbers' reciprocals. The formula for finding the N-th harmonic number is:

Hn = 1 + 1/2 + 1/3 + ... + 1/n

Let's write a Python program that gets an integer N as input and returns the N-th harmonic number as output.

def nth_harmonic_number(N: int) -> float:
    """
    Returns the N-th harmonic number
    """
    harmonic_number = 1
    for i in range(2, N + 1):
        harmonic_number += 1 / i
    return harmonic_number

Here, we have defined a function nth_harmonic_number that takes an integer N as input and returns a float as output, which is the N-th harmonic number. We have initialized the first harmonic number to 1 and then used a loop to calculate the sum of the first N natural numbers' reciprocals. Finally, we return the calculated harmonic number.

To test our program, let's call the nth_harmonic_number function with an argument N equal to 5.

print(nth_harmonic_number(5))  # Output: 2.283333333333333

Here, the output is a float number, which is the 5-th harmonic number. The output is rounded off to 15 decimal places by default.

You can use this program to find the N-th harmonic number for any value of N. The program can be modified to take user input for the value of N or generate a list of harmonic numbers.