2

I need to create a large array of integers in fortran which contains only 1 and -1. Could someone please suggest me how to define such an array that takes minimum possible memory space?

Thank you

Glenn Randers-Pehrson
  • 11,940
  • 3
  • 37
  • 61
  • Is minimizing memory space the only goal? Or does the solution need to be performant as well? – mgilson Mar 21 '14 at 16:36
  • minimizing memory is the main goal. The numbers 1 and -1 stored in the array are later multiplied with another variables, and I don't think that multiplication can be optimized anyway by reducing the size of array that defines "sign". – user3382401 Mar 21 '14 at 16:56
  • How big is "large" for your array? – Kyle Kanos Mar 21 '14 at 18:23
  • Let's say few hundred MB on disk. Since I have other variables as well, anything I save on the integer array in question would leave me with some extra space for others. – user3382401 Mar 21 '14 at 19:11

2 Answers2

2

An easy approach:

use ISO_FORTRAN_ENV

integer (INT8), dimension (N) :: array

That will give you byte-sized integers. (Unless the compiler actually chooses to implement them with larger integers, which seems implausible but is probably allowed.)

If the array is truly huge and won't fit into storage, you could access bits within variables, but that would not be a simple array.

M. S. B.
  • 28,968
  • 2
  • 46
  • 73
1

If you convert all of your -1 to 0 then you only need one bit per member of your array. Given such a transformed array that contains only 1 and 0, it's not hard to pack it into 32-bit or whatever size integers you like.

Glenn Randers-Pehrson
  • 11,940
  • 3
  • 37
  • 61