133k views
5 votes
Calculating the sin of an Angle The numerical value of cos(x) can easily be determined using the Visual Basic sin function, provided x (in radians) is given as an argument. The value of cos(x) can also be approximated by the series The accuracy of this approximation increases as the number of terms in the series (n) increases. In principle, the summation results in an exact answer when n becomes infinite. As a practical matter, the summation is usually sufficiently accurate for modestly large values of n (say, n = 5 or n = 6). Develop a visual Basic program that evaluates cos(x) using the first n terms of the series expansion. The values of x (in degrees) and n will be input values. When evaluating the series expansion, calculate Factorial using a Sub procedure. Input and output values using message boxes.

User Ckaserer
by
5.5k points

1 Answer

2 votes

Answer:

Visual Basic program

Sub cosApprox()

' Variable declaration

Dim x, seriesSum, exactValue As Double

' Variable for holding result at each iteration

seriesSum = 0

' Initializing x value

x = CDbl(InputBox("Enter x value: ", "Cos Approx", "0"))

n = CInt(InputBox("Enter n value: ", "Cos Approx", "0"))

' Iterating for n terms

For term = 0 To n

' Calculating current value and accumulating total result

seriesSum = seriesSum + (((-1) ^ term) ((x ^ (term 2)) / (WorksheetFunction.Fact((term * 2)))))

' Incrementing loop variable

Next term

' Storing exact value

exactValue = Cos(x)

' Displaying result

MsgBox ("Approximation Value: cos(" & x & "): " & seriesSum & vbNewLine & vbNewLine & "Exact Value: cos(" & x & "): " & exactValue)

End Sub

' Factorial function

Public Function factorial(ByVal n As Integer) As Long

' Base Case

If ((n = 0) Or (n = 1)) Then

factorial = 1

Else

' Recursive case

factorial = factorial(n - 1) * n

End If

End Function

User Ghazni
by
4.9k points