Nth term of a Leibniz Series

23 views (last 30 days)
Eric Brown
Eric Brown on 25 Feb 2022
Answered: Onimisi on 22 Feb 2023
I'm trying to create a function that will take a signle input (N) and output the Nth term in the Leibniz Series but for some reason my code keeps failing to pass these test: First term check, Check random variable.
Here is my function and how i am calling it.
test = LeibnizTerm(7)
function y = LeibnizTerm(N)
y = (-1)^N/(2*N+1);
end

Accepted Answer

Voss
Voss on 25 Feb 2022
It depends on if the first term should correspond to input N == 0 or input N == 1. If it's N == 0, I think it's ok how you have it.
LeibnizTerm(0)
ans = 1
LeibnizTerm(1)
ans = -0.3333
LeibnizTerm(2)
ans = 0.2000
If it should start with N == 1, then you have to make a couple of adjustments (see modified function LeibnizTerm1 below).
LeibnizTerm1(1)
ans = 1
LeibnizTerm1(2)
ans = -0.3333
LeibnizTerm1(3)
ans = 0.2000
function y = LeibnizTerm(N)
y = (-1)^N/(2*N+1);
end
function y = LeibnizTerm1(N)
y = (-1)^(N+1)/(2*N-1);
end

More Answers (2)

Onimisi
Onimisi on 22 Feb 2023
n=0:19
x=(1)*1./((2*n)+1)
y=x.*(-1).^n
LeibnizTerms=y

Onimisi
Onimisi on 22 Feb 2023
n=0:19
n = 1×20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
x=(1)*1./((2*n)+1)
x = 1×20
1.0000 0.3333 0.2000 0.1429 0.1111 0.0909 0.0769 0.0667 0.0588 0.0526 0.0476 0.0435 0.0400 0.0370 0.0345 0.0323 0.0303 0.0286 0.0270 0.0256
y=x.*(-1).^n
y = 1×20
1.0000 -0.3333 0.2000 -0.1429 0.1111 -0.0909 0.0769 -0.0667 0.0588 -0.0526 0.0476 -0.0435 0.0400 -0.0370 0.0345 -0.0323 0.0303 -0.0286 0.0270 -0.0256
LeibnizTerms=y
LeibnizTerms = 1×20
1.0000 -0.3333 0.2000 -0.1429 0.1111 -0.0909 0.0769 -0.0667 0.0588 -0.0526 0.0476 -0.0435 0.0400 -0.0370 0.0345 -0.0323 0.0303 -0.0286 0.0270 -0.0256

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!