Boolean conversion to double in Fortran

I'm looking for a bulletproof way to convert boolean type variables into a real type that will work in both ifort and gfortran. The following actions are performed in ifort, but not in gfortran:

logical :: a real :: b a = .true. b = dble(a) 

The error caused by gfortran is

 b = dble(a) 1 Error: 'a' argument of 'dble' intrinsic at (1) must be a numeric type 

It's obvious that. should map to 1.d0 and .false. to 0.d0. What is the best way to do this?

+6
source share
3 answers

I'm not sure if there is a built-in tool that does this. I don't know why ifort accepts this, and I assume that this is compiler-specific functionality.

an option for this, in particular, since you want it to be bullet proof, you need to create your own function.

I have not tested this, but the following may work:

 double precision function logic2dbl(a) logical, intent(in) :: a if (a) then logic2dbl = 1.d0 else logic2dbl = 0.d0 end if end function logic2dbl 
+6
source

In addition to writing a function to process it, you can also directly use the built-in merge function: b = merge(1.d0, 0.d0, a) . Or you can write a routine for a specific purpose that does this, so you can just type b = a .

+8
source

In gfortran, I use the built-in TRANSFER for this type of work. Assuming the integer variable my_int, then:

  my_int = transfer(.false.,my_int) 

the result of my_int is 0, as expected.

0
source

All Articles