Prompt
Answer
Pseudo Code for Evaluating the Sine Function Using an Infinite Series
Overview
The objective is to evaluate the sine function using the Taylor series expansion up to a specified order ( n ). The algorithm will compute and print the values of ( \sin(x) ) as each term is added, and will also compute and display the percent relative error compared to the actual sine value.
Key Concepts
- Sine Function Taylor Series: The sine function can be approximated by the series: [ \sin(x) = \sum_{k=0}^{n} \frac{(-1)^k x^{2k+1}}{(2k+1)!} ]
- Percent Relative Error: This is calculated as: [ \text{percent_relative_error} = \left| \frac{\text{actual_value} - \text{computed_value}}{\text{actual_value}} \right| \times 100 ]
Pseudo Code
FUNCTION computeSineAndError(x, n)
DECLARE actualValue AS FLOAT
DECLARE computedValue AS FLOAT
DECLARE error AS FLOAT
DECLARE term AS FLOAT
DECLARE factorial AS INTEGER
DECLARE powerFactor AS FLOAT
DECLARE percentRelativeError AS FLOAT
SET actualValue = sin(x) // Compute the actual sine value
computedValue = 0 // Initialize computed sine value
// Loop through each term up to n
FOR k FROM 0 TO n DO
IF k == 0 THEN
term = x // First term is x^1 / 1!
ELSE
// Calculate the factorial and power factor
factorial = FACTORIAL(2 * k + 1)
powerFactor = POWER(x, 2 * k + 1)
term = ((-1)^k * powerFactor) / factorial // Compute the k-th term
// Update the computed sine value
computedValue = computedValue + term
// Print the current term and computed sine value
PRINT "Term: ", term
PRINT "Computed sin(x): ", computedValue
// Calculate percent relative error
IF actualValue != 0 THEN
percentRelativeError = ABS((actualValue - computedValue) / actualValue) * 100
PRINT "Percent Relative Error: ", percentRelativeError
ELSE
PRINT "Actual value is 0, Relative error is undefined"
END IF
END FOR
END FUNCTION
FUNCTION FACTORIAL(n)
DECLARE result AS INTEGER
SET result = 1
FOR i FROM 1 TO n DO
result = result * i
END FOR
RETURN result
END FUNCTION
FUNCTION POWER(base, exponent)
DECLARE result AS FLOAT
SET result = 1
FOR i FROM 1 TO exponent DO
result = result * base
END FOR
RETURN result
END FUNCTION
Explanation
- computeSineAndError(x, n): This function computes the sine of ( x ) and prints out each term of the series, along with the cumulative sine value and the percent relative error.
- FACTORIAL(n): Computes the factorial of ( n ) through iterative multiplication.
- POWER(base, exponent): Raises the base to the power of the exponent using iterative multiplication.
Conclusion
This pseudo code outlines a clear and structured approach to calculating the sine function using its Taylor series expansion, while also allowing for the evaluation of the accuracy of the approximation through the percent relative error.
Description
This pseudo code demonstrates how to compute the sine function using Taylor series expansion, print each term, and calculate the percent relative error compared to the actual sine value for enhanced accuracy evaluation.