0

I'm trying to find a way to create a number pattern like the one below

0,1,-2,3,-4,5....

Please note: it needs to go to 200000, but I will be splitting them up into groups of 2000.

I found a formula that looks like it would work on http://oeis.org/A181983, but when I create the formula in MATLAB / Octave, the numbers don't match up:

f_num= @(x) x / (1 + x)^2;
numval = f_num(1)
numval =  0.25000

Is there another way I should be doing this?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Rick T
  • 3,349
  • 10
  • 54
  • 119

2 Answers2

6

Method #1 - Using (-1)^x

Just use a linear increment operator to go from 0 to 200000 and multiply the sequence by (-1)^(x+1) to allow the sign of the sequence to alternate:

x = 0:200000;
y = ((-1).^(x+1)) .* x;

The addition of the +1 is important so that the even positions get a positive sign while the odd positions get a negative sign.

Method #2 - Using indexing

Alternatively, you can declare the same array from 0 to 200000, index into every even position and negate the sign:

x = 0:200000;
x(2:2:end) = -x(2:2:end);

Method #3 - Using trigonometry and integers

One more to throw into the mix. You know that for cos(x*pi), the output is -1 when x is odd and the output is 1 when x is even. We need to flip this for your case and ultimately use this alternating sequence to multiply with the same array going from 0 to 200000, and therefore:

x = 0:200000;
y = (-cos(x*pi)).*x;

Aside

Interestingly enough, (-1)^x is also equal to exp(i*pi*x) for all values of x that are integer. We can verify this by using Euler's formula where: exp(i*pi*x) = cos(pi*x) + i*sin(pi*x). Since i*sin(pi*x) = 0 for all x belonging to an integer, we really get exp(i*pi*x) = cos(pi*x). Substituting even numbers of x will give us 1 while odd numbers of x will give us -1, and hence exp(i*pi*x) = cos(pi*x) = (-1)^x for all x belonging to integers.

Also, (-1)^(x+1) = -(-1)^x = -cos(x*pi) for all x belonging to integers and so the first method is really equal to the third method anyway!

rayryeng
  • 102,964
  • 22
  • 184
  • 193
1

try

f_num= @(x) x * (-1)^(x+1);
Loreno Heer
  • 329
  • 5
  • 12