import math
def sum_of_series(n):
"""
Calculates the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/N!
:param n: The number of terms in the series
:return: The sum of the series
"""
if n <= 0:
return "N should be a positive integer."
total_sum = 0
for i in range(1, n + 1):
total_sum += 1 / math.factorial(i)
return total_sum
try:
N = int(input("Enter a positive integer N: "))
if N <= 0:
print("Please enter a positive integer.")
else:
result = sum_of_series(N)
print(f"The sum of the series for N={N} is: {result:.6f}")
except ValueError:
print("Invalid input! Please enter a positive integer.")
#source code --> clcoding.com
Code Explanation:
1. Importing the math module:
import math
The math module provides access to mathematical functions, including math.factorial() used in this program.
2. Function Definition:
def sum_of_series(n):
"""
Calculates the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/N!
:param n: The number of terms in the series
:return: The sum of the series
"""
This function calculates the sum of the series up to ๐ terms.
3. Input Validation:
if n <= 0:
return "N should be a positive integer."
Ensures that N is a positive integer. If N≤0, an error message is returned.
4. Series Calculation:
total_sum = 0
for i in range(1, n + 1):
total_sum += 1 / math.factorial(i)
total_sum: Accumulates the sum of the series. Initially set to 0.
for i in range(1, n + 1): Loops through integers from 1 to ๐
math.factorial(i): Computes i!, the factorial of ๐
1 / math.factorial(i): Adds the term 1/๐! to the total sum.
5. Returning the Result:
return total_sum
Returns the computed sum of the series.
6. User Input Handling:
try:
N = int(input("Enter a positive integer N: "))
if N <= 0:
print("Please enter a positive integer.")
else:
result = sum_of_series(N)
print(f"The sum of the series for N={N} is: {result:.6f}")
except ValueError:
print("Invalid input! Please enter a positive integer.")
try block:
Prompts the user for an integer input for ๐.
If the user enters a valid positive integer:
Checks if
N>0. If not, prints an error message.
Otherwise, calls sum_of_series(N) to compute the sum and prints the result with six decimal places.
except block:
Handles invalid inputs (e.g., entering a string or decimal) and displays an error message.
0 Comments:
Post a Comment