Certainly! Below is a Python program to model specific mathematical equations related to the subject of algorithms. The program will demonstrate the usage of functions to solve a common algorithmic problem: finding the roots of a quadratic equation.
« `python
import math
def quadratic_roots(a, b, c):
« » »
Calculate the roots of a quadratic equation ax^2 + bx + c = 0.
Parameters:
a (float): Coefficient of x^2
b (float): Coefficient of x
c (float): Constant term
Returns:
tuple: A tuple containing the two roots of the quadratic equation.
« » »
# Calculate the discriminant
discriminant = b2 – 4*a*c
# Check if the discriminant is positive, zero, or negative
if discriminant > 0:
# Two distinct real roots
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b – math.sqrt(discriminant)) / (2*a)
return root1, root2
elif discriminant == 0:
# One real root (both roots are the same)
root = -b / (2*a)
return root, root
else:
# No real roots (complex roots)
real_part = -b / (2*a)
imaginary_part = math.sqrt(-discriminant) / (2*a)
root1 = complex(real_part, imaginary_part)
root2 = complex(real_part, -imaginary_part)
return root1, root2
def main():
« » »
Main function to test the quadratic_roots function.
« » »
# Coefficients of the quadratic equation
a = float(input(« Enter the coefficient of x^2 (a): « ))
b = float(input(« Enter the coefficient of x (b): « ))
c = float(input(« Enter the constant term (c): « ))
# Calculate the roots
roots = quadratic_roots(a, b, c)
# Display the results
print(f »The roots of the quadratic equation {a}x^2 + {b}x + {c} = 0 are: »)
if isinstance(roots[0], complex):
print(f »Root 1: {roots[0]} »)
print(f »Root 2: {roots[1]} »)
else:
print(f »Root 1: {roots[0]} »)
print(f »Root 2: {roots[1]} »)
if __name__ == « __main__ »:
main()
« `
### Explanation:
1. Function Definition: The `quadratic_roots` function takes three parameters `a`, `b`, and `c` which are the coefficients of the quadratic equation \( ax^2 + bx + c = 0 \).
2. Discriminant Calculation: The discriminant is calculated using the formula \( b^2 – 4ac \). The discriminant determines the nature of the roots.
3. Root Calculation:
– If the discriminant is positive, the equation has two distinct real roots.
– If the discriminant is zero, the equation has one real root (both roots are the same).
– If the discriminant is negative, the equation has two complex roots.
4. Main Function: The `main` function prompts the user to input the coefficients \( a \), \( b \), and \( c \). It then calculates the roots using the `quadratic_roots` function and prints the results.
5. Execution: The `if __name__ == « __main__ »:` block ensures that the `main` function is called when the script is run directly.
This program demonstrates the implementation of an algorithm to solve a specific mathematical problem, showcasing the use of functions and conditional statements in Python.