6
$\begingroup$

I'm trying to create a user-defined function that computes the equivalent resistance of $n$ resistors in parallel.

As we know, such formula is:

$R_\text{eq.p} = \dfrac{1}{\displaystyle\sum_{k=1}^{n} \dfrac{1}{R_k}} = \left( \displaystyle\sum_{k=1}^{n} R_k^{-1} \right)^{-1} \tag*{}$

The code would seem straight forward. I tried:

Rp[list_] := 1/Sum[1/list[[k]], {k, Length[list]}];
Attributes[Rp] = {Listable};

where I'm using Listable because the input of the function is a list/vector. To test it, I created the list test = {1, 2, 3}, yet when I enter Rp[test] I get the error Power: Infinite expression 1/0 encountered. Why isn't this working?

$\endgroup$
2
  • 1
    $\begingroup$ You are misinterpreting the attribute Listable. It is not used when the basic function is defined for an argument that is a List. Rather Listable is used when the function is defined for a single argument and you want each element of a List to be operated on individually. That is, for a Listable function, f[{a, b, c}] is evaluated as if you had entered {f[a], f[b], f[c]} $\endgroup$
    – Bob Hanlon
    Commented Mar 24, 2022 at 0:37
  • 1
    $\begingroup$ Just use Harmonicmean and divide by the list size. $\endgroup$ Commented Mar 24, 2022 at 18:22

3 Answers 3

16
$\begingroup$

Sum is really for symbolic sums. It's clumsy here. I suggest:

Rp[r_List] := 1/Total[1/r]
$\endgroup$
2
  • 1
    $\begingroup$ (+1) very clever and elegant!!! $\endgroup$
    – bmf
    Commented Mar 23, 2022 at 22:22
  • $\begingroup$ @bmf I don't think it's particularly clever. When you have a language that supports operations on whole arrays, it's just much easier to use that capability than to do everything element by element. $\endgroup$
    – John Doty
    Commented Mar 24, 2022 at 14:36
3
$\begingroup$
Quit[]

Rp[list_] := 1/Sum[1/list[[k]], {k, Length[list]}];

test = {1, 2, 3}

and then either

Rp[test]

or my preference

Rp@test

to get

6/11

which is the right result; see

(1/1 + 1/2 + 1/3)^-1

by a direct application of the formula.

$\endgroup$
2
$\begingroup$
Clear[Rp]
Rp[rin_List] := Module[{r},
  r = DeleteCases[rin, \[Infinity]];
  If[Total[r] === 0 
   , \[Infinity]
   , Times @@ r/Total[Times @@@ Subsets[r, {Length@r - 1}]]
   ]
  ]

testCases = {{4 k, 4 k}, {Quantity[6, "KiloOhms"], 
    Quantity[4, "KiloOhms"]}, {1, 2, 3}, {r1, r2}, {r1, r2, r3}, {1, 
    2, 0}, {1, -1}, {1, \[Infinity]}
   };

Rp /@ testCases

enter image description here

$\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.