Skip to main content
Improved code
Source Link
Michael E2
  • 244.8k
  • 18
  • 351
  • 774

Neither fast nor slow, but it gives no errors. I Originally I used PiecewiseExpand to convert the function before passing it to one NIntegrate knows how. But it turns out NIntegrate will do it for me, if I remove the ?NumericQ from the definition of q and raise the $MaxPiecewiseCases limit to handlelet NIntegrate do some symbolic processing.

Block[{q, $MaxPiecewiseCases = 500},

  q[time_] := 
   Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, 
     d2 = 870., p2 = 5000, ph2 = 0}, 
    If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] + 
     If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]];
  
  With[Block[{int$MaxPiecewiseCases =
     Assuming[0 <= t <= 7*24*3600,
      PiecewiseExpand[q[t]]]500},
   NIntegrate[intNIntegrate[q[t], {t, 0, 7*24*3600}]
   ]
  ] // AbsoluteTiming
(*
   {54.485676384593, 133030.}
*)

Neither fast nor slow, but it gives no errors. I used PiecewiseExpand to convert the function to one NIntegrate knows how to handle.

Block[{q, $MaxPiecewiseCases = 500},

  q[time_] := 
   Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, 
     d2 = 870., p2 = 5000, ph2 = 0}, 
    If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] + 
     If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]];
  
  With[{int =
     Assuming[0 <= t <= 7*24*3600,
      PiecewiseExpand[q[t]]]},
   NIntegrate[int, {t, 0, 7*24*3600}]
   ]
  ] // AbsoluteTiming
(*
   {5.485676, 133030.}
*)

Neither fast nor slow, but it gives no errors. Originally I used PiecewiseExpand to convert the function before passing it to NIntegrate. But it turns out NIntegrate will do it for me, if I remove the ?NumericQ from the definition of q and raise the $MaxPiecewiseCases limit to let NIntegrate do some symbolic processing.

q[time_] := 
 Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, d2 = 870., p2 = 5000, ph2 = 0}, 
   If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] + 
    If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]];
  
Block[{$MaxPiecewiseCases = 500},
  NIntegrate[q[t], {t, 0, 7*24*3600}]
  ] // AbsoluteTiming
(*
   {4.384593, 133030.}
*)
Source Link
Michael E2
  • 244.8k
  • 18
  • 351
  • 774

Neither fast nor slow, but it gives no errors. I used PiecewiseExpand to convert the function to one NIntegrate knows how to handle.

Block[{q, $MaxPiecewiseCases = 500},

  q[time_] := 
   Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, 
     d2 = 870., p2 = 5000, ph2 = 0}, 
    If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] + 
     If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]];
  
  With[{int =
     Assuming[0 <= t <= 7*24*3600,
      PiecewiseExpand[q[t]]]},
   NIntegrate[int, {t, 0, 7*24*3600}]
   ]
  ] // AbsoluteTiming
(*
   {5.485676, 133030.}
*)