2
$\begingroup$

I just get started with Mathematica and I have a basic question about defining a function (I am sorry if this was asked before). I have 2 functions defined as:

lorentz[x_, x0_, linewidth_] := 1/Pi (1/2 linewidth)/((x - x0)^2 + (1/2 linewidth)^2) ;
mol[J_, dB_] := dB * J (J + 1);

I want to create a new function which combines the 2 functions above, as follows. For example in Python (that's what I used so far) I would do this:

linewidth = 0.1
dB = 0.1
def f_combined(x):
  f = 0
  for J in range(1,10):
    f = f + lorentz(x,mol(J,dB),linewidth)
  return f

I am not sure how to do it in Mathematica. This is what I tried:

linewidth = 0.1;
dB = 0.1;
f_combined[x_] = Sum[lorentz[x, mol[J, dB], linewidth] , {J, 1, 10}];

But it doesn't seem to work. Can someone help me with this? Thank you!

$\endgroup$
0

2 Answers 2

3
$\begingroup$

Blank ( _ ) is only used as a pattern object; it cannot be used in a variable name

Clear["Global`*"]

lorentz[x_, x0_, linewidth_] := 
  1/Pi (1/2 linewidth)/((x - x0)^2 + (1/2 linewidth)^2);
mol[J_, dB_] := dB*J (J + 1);

linewidth = 1/10;
dB = 1/10;
fCombined[x_] = 
  Sum[lorentz[x, mol[J, dB], linewidth], {J, 1, 10}] // Together // 
   FullSimplify;

Plot[fCombined[x], {x, -1, 15}]

enter image description here

$\endgroup$
2
$\begingroup$

A slight variation using the Fold function (benefitting from Bob Hanlon's answer):

lorentz[x_, x0_, linewidth_] := 1/Pi (1/2 linewidth)/((x - x0)^2 + (1/2 linewidth)^2) ;
mol[J_, dB_] := dB * J (J + 1);
linewidth = 0.1;
dB = 0.1;

fCombined[x_] = 
 Fold[#1 + lorentz[x, mol[#2, dB], linewidth] &, 0, Range[10]] // 
   Together // FullSimplify

The Fold function starts at 0, folds one argument (1-10) representing an increasing J every time it executes the expression defined as the first argument, thus accumulating a sum in terms of x.

Plot[fCombined[x], {x, -1, 15}, 
 PlotStyle -> {Thin, Blue},
 GridLines -> Automatic,
 GridLinesStyle -> {{Gray, Dotted}, {Gray, Dotted}},
 PlotRange -> {{-1, 13}, {0, 7.0}},
 AspectRatio -> 0.25,
 AxesLabel -> {x, Defer@fCombined[x]},
 ImageSize -> 800]

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.