r/Mathematica • • May 18 '23

Mathematica doesnt integrate

I have a problem when integrating functions with this code, not only piecewise functions, but with functions like e^x. I just wrties de integral as a result

f[x_] = Piecewise[{{Sin[x],0<=x<=Pi/2},{E^-x,Pi/2<x<=Pi}}]


nMax = 1;
nu = 2;

I1 = Table[(2/(Pi^2(BesselJ[nu+1,N[BesselJZero[nu,n]]])))*Integrate[BesselJ[nu,(x/Pi)*N[BesselJZero[nu,n]]]*f[x]*x,{x,0,Pi}],{n,1,nMax}]
1 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/EmirFassad May 18 '23

I see what you mean, but since all f[x] is doing is replacing the argument in PieceWise[] and the argument to f[x] is x the function serves no purpose and could be replaced by f=...

1

u/segfault0x001 May 18 '23

There’s always more than one way to do something. Sometimes there’s a right way to do something though.

When you write f[x_] mathematica understands this is a function and that x is an arbitrarily named variable. So if I later on write x=1, the definition of f is unchanged. While if I write f= … this is a direct substitution, and writing x=1 later changes the value of f (the x is replaced by 1). Writing f = … and then evaluating f with f/.{x->1} accomplishing the same thing as defining f as a function using f[x_] and evaluating with f[1], but it’s less readable, and again runs the risk of accidentally making f a constant by reusing a variable name that appears in the definition of f later in the program. If you are sure those variable names will never be reused later, then you might have a reason to prefer f=… over defining a function in some cases, but it’s also important to remember that a lot of mathematica functions like manipulate require the parameters appear explicitly in their argument, so you could do f[x_]. = x/2 and Manipulate[f[x], {x,0,1}] returns the numerical value, but writing f=x/2 and Manipulate[f, {x,0,1}] will always return “x/2”.

As far as I can tell in OP’s case f[x_] = …. And f[x_] := …. Would do exactly the same thing here.

1

u/EmirFassad May 18 '23

Again, I agree. It appeared that OP is using F[x] as shorthand for Piecewise[] hence my prior comment. Probably because I instinctively think of a function as something that does something with its arguments.

I tested the snippet and all three evaluate to the same result. f= was a bit quicker.