Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalence statement

Tags:

fortran

Code:

program CheckEquivalence
  integer*8 intarray(4)
  real*8 realarray(4)

  equivalence(realarray,intarray)
  realarray(3) = 3
  intarray(4) = 4
  realarray(1) = 1.0
  realarray(2) = 2.0

  do i = 1,4
    write(,) 'All real ', realarray(i)
  enddo
  do i = 1,4
    write(,) 'All int ', intarray(i)
  enddo
  do i = 1,3
    write(,) 'Some real ', realarray(i)
  enddo
  write(,) 'Last int ', intarray(4)
end

output is:

All real 1.
All real 2.
All real 3. 
All real 1.97626258E-323
All int 4607182418800017408 
All int 4611686018427387904
All int 4613937818241073152 
All int 4
Some real 1. 
Some real 2. 
Some real 3.
Last int 4

I tried one sample code to understand how equivalence works. My query is in which format internally data is getting stored and any algorithm from which I can get theoretical same value?

like image 465
Kittu Avatar asked Dec 21 '11 01:12

Kittu


2 Answers

As answered here:

equivalence statements in fortran

There is no conversion between the two values. It is stored based on what you write to the variable and interpreted based on how you access it. So if you write to the REAL a real-value, and then try to print the integer variable, you will get garbage. And vice versa.

Generally speaking, do not use EQUIVALENCE statements. They are a bad idea and deprecated. If you are writing new code, don't put them in -- if you are trying to interpret old code, they are typically used to create compact storage in memory by reusing the same location for different purposes.

like image 154
tpg2114 Avatar answered Sep 20 '22 14:09

tpg2114


Yes, as already answered there is extremely little reason to use EQUIVALENCE. It was commonly used decades ago to conserve memory by overlapping arrays. It can also be used for low-level non-portable manipulations. If you store a real number and output as an integer, the results will be non-portable, outside of the language standard, depending on the numeric representation of the hardware that you are using. There are occasional reasons to do bit-level manipulations, e.g., if you read in binary data and then determine what type it is. Or to do byte-swapping. The modern replacement for EQUIVALENCE is the "transfer" intrinsic function.

like image 27
M. S. B. Avatar answered Sep 16 '22 14:09

M. S. B.