VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Calculate Sin(x), e(x) , and Pi

by Jonathon Lopez (2 Submissions)
Category: Math/Dates
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (3 Votes)

This code allows you to calculate Sin(x), e^(x), and Pi without using any of the built-in VB functions

Assumes
The way this code works is by using what is called Taylor Expansion. By generating a taylor series using derivatives it is possible to take the sum of the elements in that series to find such functions as Sin(x) and even Pi.

Rate Calculate Sin(x), e(x) , and Pi

'Sin(x) function
'Note: this is in radians, not degrees
Public Function Sine(x as Double) as Double
Dim i As Integer, sum As Double: sum = 0
'Calculate the taylor expansion of sin
For i = 1 To 10
  sum = sum + (((-1) ^ (i + 1)) * ((x) ^ (2 * i - 1)) / fact(2 * i - 1))
Next i
Sine=sum
End Function
'e^(x) function
Public Function e(x as Integer) as Double
Dim i As Integer, sum As Double: sum = 0
'Calculate the Taylor expansion of e
For i = 0 To 150
  sum = sum + (x ^ i) / fact(i)
Next i
e=sum
End Function
'Pi function
Public Function pi() as Double
Dim i As Integer, sum As Double: sum = 0
For i = 1 To 15000
  sum = sum + ((-1) ^ (i + 1)) * (1 ^ (2 * i - 1)) / (2 * i - 1)
Next i
pi = sum * 4
End Function
'Function that calculates factorials
Public Function fact(n As Integer) As Double
Dim i As Long, r As Double: r = 1
If n = 0 Then fact = 1
For i = 1 To n
  r = i * r
Next i
fact = r
End Function

Download this snippet    Add to My Saved Code

Calculate Sin(x), e(x) , and Pi Comments

No comments have been posted about Calculate Sin(x), e(x) , and Pi. Why not be the first to post a comment about Calculate Sin(x), e(x) , and Pi.

Post your comment

Subject:
Message:
0/1000 characters