Re: declare variables [message #45934] |
Tue, 18 October 2005 16:37  |
Mark Hadfield
Messages: 783 Registered: May 1995
|
Senior Member |
|
|
qian wrote:
> Hi,
>
> I am using FORTRAN and IDL at the same time, so sometime I just assume
> some FORTRAN rules when using IDL. I just find out that the variable
> type can change within an IDL program, even you declare it to be some
> specific type. For example:
>
> data=dblarr(2)
>
> data=[2.3, 3.4]
>
> then now, 'data' is a single precision array.
>
> if I type
>
> data=[2,3]
>
> then it is an integer array.., and data(0)/data(1) = 0 !
>
> I know I should be more careful when programming, always using:
>
> data=[2.3D,4.5D]
>
> But if I read in data from other files, in which '1' actually means
> '1.0', is it possible I can re-inforce the array to be certain type (or
> let the variables to be certain type throughtout the whole program)? So
> even if I type d=1, it is still a real number?
As other respondents have pointed out, IDL is a dynamically typed
language so you can't ensure a given variable name is always associated
with data of a given type or shape. Still, there are some things you can
do to prevent unintended changes of type.
For example, consider the following
IDL> data=[2.3,3.4]
IDL> data[*] = [2,3]
IDL> print, data
2.00000 3.00000
The 1st defines data to be a 1-dimensional, 2-element, floating point
array. The 2nd assigns new values to the elements of d, but does not
change the type or shape. The 3rd confirms that the variable named data
is still floating point.
Consider another example
IDL> data = fltarr(2)
IDL> read, data
: 2 3
IDL> print, data
2.00000 3.00000
(where the colon indicates that IDL is accepting input from the
keyboard--reading from a file has the same result). Here we define data,
again as a a 1-dimensional, 2-element, floating point array, then read
in values. It doesn't matter that the numbers we read in look like
integers--the type and shape of the variable are not altered.
--
Mark Hadfield "Kei puwaha te tai nei, Hoea tahi tatou"
m.hadfield@niwa.co.nz
National Institute for Water and Atmospheric Research (NIWA)
|
|
|