TransWikia.com

avoid use of a global variable

Mathematica Asked by picop on January 14, 2021

I am writing some piece of code to do some numerical integration by hand. To this end, I discretize the interval [0,1] on a grid $x_0=0,x_1,dots,x_{Nmax-1},x_{Nmax}=1$ and compute the value of the integral on elementary intervals $[x_{n-1},x_{n}]$, I call the resulting function B[n]. (My actual situation is more complicated because actually each integral also depends on another point of the grid so I really have B[n,m]). My problem is that for the extremal values $x_0,x_1,x_{Nmax-1},x_Nmax$ the function is different and I need to set this by hand.
For instance

B[n_]=Log[x[n]-x[n-1]];
B[1]=Log[x[1]]/2;
B[Nmax-1]=Log[x[Nmax-1]-1]/2+1;
B[Nmax]=0;

This is really a sort of baby example but my problem here is what to do with the quantity Nmax. In some cases I have to use things like B[n/;n>=1&&n<=Nmax-1] but that’s a real pain to know if subsequent definitions of this function B will clash with this, or if they require that Nmax was given a value before being evaluated, etc. In the final version of the code, the grid would be defined before evaluating all those definitions, but I can’t help but thinking that there must be a cleaner way to do this. So far, I have been doing a mixture of playing with = versus := and also calling function BNmaxminusone and this sort of things, but that’s really ugly.

One Answer

If you don't want a global variable Nmax, you can use With to bake the value into B:

With[{Nmax = 10},
  B[n_]=Log[x[n]-x[n-1]];
  B[1]=Log[x[1]]/2;
  B[Nmax-1]=Log[x[Nmax-1]-1]/2+1;
  B[Nmax]=0;
]

You can look at the DownValues or Definition of B to check that Nmax has disappeared and been replaced with 10 in all definitions of B.

Answered by Sjoerd Smit on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP