0
$\begingroup$

I should define a function which sums up from k=0 to 100, with x=1; using the Do function and modules; without using the Sum function

I tried it this way:

blub[x_, p_]:=Do[blub=((-1)^k/x^k), {k, 1, p}]
blub[1, 100]

Problems:

  1. I don't get any output
  2. I don't get why I would need a module

I would be glad if someone could help me.

Thanks for the fast help, Solution number 2 fits perfect for what I want.

Is there a posibility that I use a module inside the iterator? So that I can use my function this way.

v=0;    
f[x_, n_]:=Do[v +=((-1)^n/x^n), {n, 1, n}]
f[1, 100]
v

Is there a posibility to make this work without changing one of the n's into another variable name (I`m aware that I double defined one variable)

$\endgroup$

1 Answer 1

7
$\begingroup$

The following I hope will assist you:

b = 0;
blub[x_, p_] := Do[b += ((-1)^k/x^k), {k, 1, p}]
blub[1, 100]
b

or achieving the output:

f[x_, p_] := Module[{v = 0},
  Do[v += ((-1)^k/x^k), {k, 1, p}];
  v]

There are many ways to achieve this result, e.g.

s[x_, p_] := Sum[(-1)^k/x^k, {k, 1, p}]
r[x_, p_] := Total[(-1)^#/x^# & /@ Range[p]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.