Write a R program to find roots of a quadratic equation

1. Introduction

This R program finds the roots of a quadratic equation of the form ax^2 + bx + c = 0. It uses the quadratic formula: roots = (-b ± sqrt(b^2 - 4ac)) / 2a.

2. Program Steps

1. Define the coefficients of the quadratic equation (a, b, c).

2. Calculate the discriminant (b^2 - 4ac).

3. Calculate the roots using the quadratic formula.

4. Print the roots.

3. Code Program

# Step 1: Define coefficients of the quadratic equation
a <- 1
b <- -3
c <- 2

# Step 2: Calculate the discriminant
discriminant <- b^2 - 4 * a * c

# Step 3: Calculate the roots
root1 <- (-b + sqrt(discriminant)) / (2 * a)
root2 <- (-b - sqrt(discriminant)) / (2 * a)

# Step 4: Print the roots
print("Roots of the quadratic equation are:")
print(root1)
print(root2)

Output:

Roots of the quadratic equation are:
[2]
[1]

Explanation:

1. a <- 1, b <- -3, c <- 2: Sets the coefficients of the quadratic equation.

2. discriminant <- b^2 - 4 * a * c: Calculates the discriminant, which is used to determine the nature of the roots.

3. root1 <- (-b + sqrt(discriminant)) / (2 * a) and root2 <- (-b - sqrt(discriminant)) / (2 * a): Calculate the two roots using the quadratic formula.

4. print("Roots of the quadratic equation are:"), print(root1), print(root2): Print the calculated roots of the equation.


Comments