1
$\begingroup$

For a fake function like:

fun[x_] := x^0/x!;

and list:

list={0,0,0.1,0.2,0.9,0.8,0,0};

It will get error in this way cause the 0^0 is indeterminate:

fun[list]

In that case,I want to just leave the 0 element in the list as it is and only calculate the element that larger than 0. Are there some easy and fast way to implement this?

$\endgroup$
  • 4
    $\begingroup$ fun[x_?Positive] := x^0/x!;fun[0]=0; $\endgroup$ – Alan May 21 '18 at 16:29
  • $\begingroup$ fun[x_] := x^0/x! /; x > 0 fun[0] = 0; fun /@ list $\endgroup$ – Fraccalo May 21 '18 at 16:31
4
$\begingroup$

You can define a special case for the $0$ input.

ClearAll[fun]
fun[0] = 0
fun[x_] := x^0/x!
SetAttributes[fun, Listable]

fun[list]

(* Out: {0, 0, 1.05114, 1.08912, 1.03975, 1.07367, 0, 0} *)

Notice that you can use your original function on a list directly (i.e. fun[list] instead of mapping it over a list as in fun /@ list), because you take advantage of the Listable attributes of the operations used in your function.

If you define the special case for $0$ input, however, it is easiest to make your function explicitly Listable so that it itself automatically threads over lists and the $0$ special case fires appropriately.

$\endgroup$
  • $\begingroup$ Thank you for the detailed answer! $\endgroup$ – cj9435042 May 21 '18 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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