Consider again the following series: 1+ Sigma^k = infinity _k=1 (-1)^k * (x/2)^2
ID: 3800062 • Letter: C
Question
Consider again the following series: 1+ Sigma^k = infinity _k=1 (-1)^k * (x/2)^2k/(k!)^2 For x = 1.5 write a VBA program to evaluate this series. Use a Do While loop to continue the summation until the magnitude of a term is less than 0.5EE-7 or 20 summation terms are computed. Handle input and output in the main sub. Evaluate the series in a subordinate sub. Evaluate k! in a user-defined function using a for loop. Output the value of your series, the last term computed, and the last value of k used.Explanation / Answer
The VB Code
Imports System.Collections.Generic
Imports System.Text
Imports System.Threading.Tasks
Namespace ConsoleApplication3
Class Program
Private Shared Sub Main(args As String())
Dim a As Double = 5E-07
Dim counter As Integer = 0, k As Integer = 0
Dim sum As Double = 0.0
Dim x As Double = 1.5
Do
Dim factK As Long = fact(k)
sum = sum + (Math.Pow(-1, k) * (Math.Pow((x / 2), (2 * k)))) / Math.Pow(factK, 2)
counter += 1
k += 1
Loop While sum > a AndAlso counter < 21
Console.WriteLine(sum)
Console.ReadLine()
End Sub
Private Shared Function fact(k As Integer) As Long
Dim facto As Long = 1
For i As Integer = 1 To k
fact = fact * i
Next
Return fact
End Function
End Class
End Namespace
The logic is successfully implemented in above code. but there might be some compiler error like No accessible 'Main' method with an appropriate signature was found in 'ConsoleApplication5'. ConsoleApplication5 . Just correct them accordingly for your Visual studio.
The C# code also for the same
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
double a = 0.0000005;
int counter = 0,k=0;
double sum = 0.0;
double x = 1.5;
do
{
long factK = fact(k);
sum = sum + (Math.Pow(-1, k) * (Math.Pow((x / 2), (2 * k)))) / Math.Pow(factK, 2);
counter++;
k++;
} while (sum > a && counter < 21);
Console.WriteLine(sum);
Console.ReadLine();
}
private static long fact(int k)
{
long fact = 1;
for(int i=1;i<=k;i++)
{
fact = fact * i;
}
return fact;
}
}
}
It will run perfectly fine.