5

Here is my code:

h = .2; 
m = .04;
k = 4/Pi^2;
L = 4;
n = L/h; 
s = k*m/h^2;
A = SparseArray[{Band[{1, 1}] -> 1.0 + 2.0*s, Band[{2, 1}] -> -s, 
    Band[{1, 2}] -> -s}, n + 1];

Here's the error:

SparseArray::dims: The dimensions 21.` in SparseArray[{Band[{1,1}]->1.81057,Band[{2,1}]->-0.405285,Band[{1,2}]->-0.405285},21.] are not given as a list of positive machine integers. >>

I've been experimenting with this for quite a while now and can't seem to figure out what's wrong. Any ideas?

VividD
  • 3,660
  • 4
  • 26
  • 42
David
  • 213
  • 1
  • 4

1 Answers1

9

The message tells you what`s wrong:

SparseArray::dims: The dimensions 11.` in ...are not given as a list of positive machine integers.

You should use something like Round[n+1] as last part.

Your comment

Isn't n +1 an integer though? 4/.2 + 1 = 21?

No. Mathematica makes a distinction between exact Integers and numeric values. In your formula, the .2 is a numeric value (in contrast to 2/10!) and therefore, the result is 21.0.

result=4/.2+1;
IntegerQ[result]
Head[result]
IntegerQ[Round[result]]
(*
Out[13]= False
Out[14]= Real
Out[15]= True
*)

For further reading please see here or search the forum.

halirutan
  • 112,764
  • 7
  • 263
  • 474
  • Isn't n +1 an integer though? 4/.2 + 1 = 21? – David Dec 06 '12 at 07:16
  • 1
    @David No, $n+1$ is a the real number 21.0. You might want to read up on types of numbers: http://reference.wolfram.com/mathematica/tutorial/TypesOfNumbers.html – Mark McClure Dec 06 '12 at 07:26
  • ok. That kind of makes sense. I just figured the language would be sufficiently robust to allow for real numbers equal to an integer to be used as an integer. Is there a reason why it doesn't support this? – David Dec 06 '12 at 07:31
  • 4
    @David Yes, there are very good reasons to distinguish between real numbers and integers - this is common across a most programming languages. Internally, the arithmetic is very different. Exact arithmetic, between integers for example, is more costly computationally - so, why do it if the programmer doesn't need it? – Mark McClure Dec 06 '12 at 07:37