Numerical methods The value of n can be calculated with the

Numerical methods

The value of n can be calculated with the series: pi = 4 sigma_n = 1^infinity (-1)^n-1 1/2n-1 = 4 (1 -1/3 + 1/5 + 1/7 + 1/9 1/11 + ...) Write a MATLAB program in a script file that calculates the value of pi by using n terms of the series and calculates the corresponding true relative error. (For the true value of it, use the predefined MATLAB variable pi.) Use the program to calculate it and the true relative error for: n = 10. n = 20. n = 40.

Solution

function result = piApprox(n)

    piVal = 0
    term = 0
    for i = 1 : n
        term = (power(-1, i-1) * (1/((2 * i) -1)))
        piVal = piVal + term
        %fprintf(\" i = %d, term = %f \ \",i, term);
    end
    result = 4 * piVal
end

function result = relativeError(compValue, actualValue)
   diff = actualValue - compValue
   if(diff < 0)
      diff = diff * -1
   end
   result = (diff/actualValue) * 100
end

n = 10
val = piApprox(n)

fprintf(\" n = %d, pi = %f, relative error = %f percent\ \",n,val,relativeError(val, pi) )

n = 20
val = piApprox(n)

fprintf(\" n = %d, pi = %f, relative error = %f percent\ \",n,val,relativeError(val, pi) )

n = 40
val = piApprox(n)

fprintf(\" n = %d, pi = %f, relative error = %f percent\ \",n,val,relativeError(val, pi) )


---output----

Executing the program....
$octave -qf --no-window-system main.m

Numerical methods The value of n can be calculated with the series: pi = 4 sigma_n = 1^infinity (-1)^n-1 1/2n-1 = 4 (1 -1/3 + 1/5 + 1/7 + 1/9 1/11 + ...) Write

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site