Trying to code a vb console application that calculates sin(x). But it compares the approximated value of sin x with an intrinsic function of sin(x) and gives the error as a percentage. There is something wrong with the calculation that i cannot crack. Any help would be appreciated.
Code:
Module Module1
'The main
Sub Main()
'The variables
Dim x As Integer
Dim n As Integer
Dim approximated_Value As Double
Dim i As Integer
Dim correctValue As Double
Dim Err As Double
Dim xradian As Double
'tell user to input values of x and n
Console.WriteLine("Enter the value of x")
x = Console.ReadLine()
'convert the input value of x from degrees to radians
xradian = x * Math.PI / 180
Console.WriteLine("Enter the value of n")
n = Console.ReadLine()
correctValue = Math.Sin(xradian)
Console.WriteLine("approximated value and error as a percentage: ")
Console.WriteLine(" ")
approximated_Value = 0
'for next loop to calculate the approximated value and the error
For i = 0 To n
approximated_Value = ((-1) ^ i) * (x ^ (2 * i + 1)) / Factorial(2 * i + 1) 'calculate the approximated value
Err = ((((correctValue - approximated_Value) / correctValue) ^ 2) ^ 1 / 2) * 100 'calculate the error
Next
Console.WriteLine("approximated value =" & approximated_Value) 'Output result for the approximated value
Console.WriteLine("error = " & Err) 'Output results for the error
Console.ReadKey()
End Sub
Function Factorial(n As Integer) As Long
Dim Fact As Long = 1
Dim i As Integer
If n = 0 Or n = 1 Then
Return Fact 'if
End If
'calculate n when greater than 2
For i = 2 To n
Fact = Fact * i
Next i
Return Fact
End Function
End Module