473,626 Members | 3,351 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Again: linking between C++ and Fortran results in incorrect result

NM
Sometimes ago I was having a problem in linking between C++ and Fortran
program. That was solved (using input from this newsgroup) using the Fortran
keyword "sequence" with the derived types (to assume contiguous space).

Now I am having problem again. In order to show the problem I have created
small program and this time there is no data straucture being passed between
C++ and Fortran.

Here is how the program looks like

file read_do_calc.f= =============== === subroutine read_do_calc()

double precision :: a,b,c,d,e,f,val

open(60,file='b inary_file',sta tus='unknown',f orm='unformatte d')
read(60) a
read(60) b
read(60) c
read(60) d
read(60) e
read(60) f

close(60)
write(*,*) a,' ',b,' ',c,' ',d,' ',e,' ',f

val = a + (b*c*d*(e*e))*f
write(*,*) 'val = ',val

return
endfile fort_main.f==== ============ program main

call read_do_calc()

endprogram mainfile main.cpp======= ====== extern "C" {
void read_do_calc_(v oid);
}

int main(void)
{
read_do_calc_() ;

return 0;
} compile read_do_calc.f
ifort -c read_do_calc.f
create the fortran programifort -o fort_prog fort_main.f read_do_calc.o
create the c++ program (either using icc or g++ , it did not matter in my
case)icc -o cpp_prog main.cpp
read_do_calc .o -L/lusr/share/software/intel/lib -lifcore

output of the two programs given below
./fort_prog -0.4303314829119 35 1.0000000000000 0 -0.7745966692414 83
-1.0000000000000 0 2.0000000000000 0 0.1388888888888 89
val = 0.0000000000000 00E+000
./cpp_prog -0.4303314829119 35 1.0000000000000 0 -0.7745966692414 83
-1.0000000000000 0 2.0000000000000 0 0.1388888888888 89
val = -6.9659989582193 66E-018Notice the value of the variable "val" is
different in the two cases.The version of ifort I am using isifort --versionifort (IFORT) 9.0 20050430Copyrig ht (C) 1985-2005 Intel

Corporation. All rights reserved.and the version of icc is>icc --versionicc
(ICC) 9.0 20050430Copyrig ht (C) 1985-2005 Intel Corporation. All rights
reserved.The file "binary_fil e" is attached. The values there was captured
from a nontrivial program whose computation looks like that of the
subroutine read_do_calc(). Can anyone please help me? What am I doing wrong
this time? Thanks.NM


Sep 15 '05 #1
13 2526
NM wrote:
Sometimes ago I was having a problem in linking between C++ and Fortran
program. That was solved (using input from this newsgroup) using the Fortran
keyword "sequence" with the derived types (to assume contiguous space). Now I am having problem again. In order to show the problem I have created
small program and this time there is no data straucture being passed between
C++ and Fortran.
(snip)
val = a + (b*c*d*(e*e))*f
(snip)
-0.4303314829119 35 1.0000000000000 0 -0.7745966692414 83
-1.0000000000000 0 2.0000000000000 0 0.1388888888888 89
val = 0.0000000000000 00E+000
(snip)
-0.4303314829119 35 1.0000000000000 0 -0.7745966692414 83
-1.0000000000000 0 2.0000000000000 0 0.1388888888888 89
val = -6.9659989582193 66E-018 Notice the value of the variable "val" is
different in the two cases.The version of ifort I am using is


There are a number of things I could say about this.

First, it is probably better to always do I/O using the language of
the main program. Sometimes the I/O system needs to be initialized.
This is less a problem than it used to be, as many use one library
to do the actual I/O in both cases.

In general, one should not rely on exact results from floating point,
especially when subtracting very similar numbers.

My guess in this case is that the Fortran main program sets the
floating point processor to 53 bit precision, where C++ sets
or leaves it at 64. The rules for allowing the compiler to do
arithmetic with more precision than is asked for are complicated,
and different between C++ and Fortran.

In any case, expecting one answer or the other from floating
point is, I believe, unwarranted.

-- glen

Sep 15 '05 #2
In article <dg**********@n ews.cs.utexas.e du>, "NM" <nm@nm.com> wrote:

.....
val = a + (b*c*d*(e*e))*f ....
./fort_prog

.... val = 0.0000000000000 00E+000
./cpp_prog
val = -6.9659989582193 66E-018
Notice the value of the variable "val" is different in the two cases.
It sure isn't *VERY* different. The difference is right about what one
would expect for double precision accuracy.
Can anyone please help me? What am I doing wrong this time?


What you are doing wrong is expecting perfect accuracy from
floating-point arithmetic. This has very little to do with programming
languages. It is instead a fundamental property of typical computer
implementations of arithmetic. You need to read up on that subject. The
document <http://docs.sun.com/source/806-3568/ncg_goldberg.ht ml> is an
excellent and oft-cited treatment of the subject (in fact, it was cited
in another thread here just a day or so ago).

In addition to that basic material, you also need to understand that a
given expression might be implemented differently in different
compilers, or even with different options of the same compiler. Those
different implementations can involve such things as different ordering
of operations or differences in storage of intermediate values in
registers. These differences can and do often result in differences in
rounding.

Because of these factors, it is a mistake to expect the results of
floating point operations to be exact except in some special
circumstances.. . and you don't have those circumstances. Floating point
operations should generally be viewed as approximations. You can select
an appropriate precision as needed to keep the approximations reasonable
for an application, but you can't reasonably expect things to be exact.
What you are doing wrong is expecting exact results.

The differences you are seeing are right around the size expected from
simple cases of rounding error. With numerically unstable algorithms,
such small differences can sometimes grow to be quite large. Perhaps
that's what drew your attention to the problem in the actual
application. (That generally indicates at east reason to question the
suitability of the algorithm used). ALgorithms that test for exact
values can behave particularly poorly.

And if you say something like "I understand all that, but...(insert
anything here)", then I'm afraid you didn't really understand. It really
doesn't matter what follows the "but". In particular, any variation of
"but it was the same expression in both languages" would indicate that
you didn't really understand.

--
Richard Maine | Good judgment comes from experience;
email: my first.last at org.domain | experience comes from bad judgment.
org: nasa, domain: gov | -- Mark Twain
Sep 15 '05 #3
Richard E Maine wrote:

(snip)
It sure isn't *VERY* different. The difference is right
about what one would expect for double precision accuracy.
(snip)
What you are doing wrong is expecting perfect accuracy from
floating-point arithmetic. This has very little to do with programming
languages. It is instead a fundamental property of typical computer
implementations of arithmetic. You need to read up on that subject. The
document <http://docs.sun.com/source/806-3568/ncg_goldberg.ht ml> is an
excellent and oft-cited treatment of the subject (in fact, it was cited
in another thread here just a day or so ago).
I 100% agree, if he expects more from floating point, that is
a mistake.
In addition to that basic material, you also need to understand that a
given expression might be implemented differently in different
compilers, or even with different options of the same compiler. Those
different implementations can involve such things as different ordering
of operations or differences in storage of intermediate values in
registers. These differences can and do often result in differences in
rounding.
In this case, though, it is the same object program. He calls the
subroutine, compiled only once, from a C++ or Fortran main program.
All the calculation is done in the subroutine.
Because of these factors, it is a mistake to expect the results of
floating point operations to be exact except in some special
circumstances.. . and you don't have those circumstances. Floating point
operations should generally be viewed as approximations. You can select
an appropriate precision as needed to keep the approximations reasonable
for an application, but you can't reasonably expect things to be exact.
What you are doing wrong is expecting exact results.
Yes. Note that similar differences have been seen for the same
expression at a different line in the same program.

(snip)
And if you say something like "I understand all that, but...(insert
anything here)", then I'm afraid you didn't really understand. It really
doesn't matter what follows the "but". In particular, any variation of
"but it was the same expression in both languages" would indicate that
you didn't really understand.


I am not completely sure I understand the way the x87 floating
point processor is initialized, but it might even be possible
to run the same .EXE file and get different results. If the
library doesn't initialize the x87 control register, and the
OS doesn't, you get whatever was there before.

If you want exact results don't use floating point.

-- glen

Sep 15 '05 #4
NM
> In this case, though, it is the same object program. He calls the
subroutine, compiled only once, from a C++ or Fortran main program.
All the calculation is done in the subroutine.
I am not expecting exact result. I know floating points are approximation of
real numbers. What I was expecting was that a subroutine would give me same
output given the same input. In the real world the nontrivial Fortran
subroutine is taking a different path because of the different result and I
did not write it.
Yes. Note that similar differences have been seen for the same
expression at a different line in the same program.
Did not get it. To test if the order was a factor in this case, I used
explicit parenthesis to didctate the order of the expression evaluation. It
did not change anyhthing.

I am not completely sure I understand the way the x87 floating
point processor is initialized, but it might even be possible
to run the same .EXE file and get different results. If the
library doesn't initialize the x87 control register, and the
OS doesn't, you get whatever was there before.

If you want exact results don't use floating point.


I thought that, since I am calling the same implementation from both C++ and
fortran using the same input, it would give me same result. Thats all.
Sep 15 '05 #5
NM wrote:

(snip)
I thought that, since I am calling the same implementation from both C++ and
fortran using the same input, it would give me same result. Thats all.


It sounds good, but it doesn't seem to be.

Part of the design of the intel math processor, starting with the 8087
about 20 years ago, was that intermediate results could have even more
precision. The internal registers are 80 bits wide.

There are many calculations where the extra bits help, but you
have no control over when they are used, and when they aren't.

It might be that Fortran is slightly more strict on not allowing the
extra precision, and the compiler you used sets 53 bit precision, though
if I remember right that doesn't affect all operations. The only way to
do it right is to store to memory and reload between each operation, but
that is generally much slower, so isn't usually done.

As all have said, if your program depends on the difference the
program is wrong and needs to be fixed.

-- glen

Sep 15 '05 #6
NM wrote:
In this case, though, it is the same object program. He calls the
subroutine, compiled only once, from a C++ or Fortran main program.
All the calculation is done in the subroutine.

I am not expecting exact result. I know floating points are approximation of
real numbers. What I was expecting was that a subroutine would give me same
output given the same input. In the real world the nontrivial Fortran
subroutine is taking a different path because of the different result and I
did not write it.

Yes. Note that similar differences have been seen for the same
expression at a different line in the same program.

Did not get it. To test if the order was a factor in this case, I used
explicit parenthesis to didctate the order of the expression evaluation. It
did not change anyhthing.

I am not completely sure I understand the way the x87 floating
point processor is initialized, but it might even be possible
to run the same .EXE file and get different results. If the
library doesn't initialize the x87 control register, and the
OS doesn't, you get whatever was there before.

If you want exact results don't use floating point.

I thought that, since I am calling the same implementation from both C++ and
fortran using the same input, it would give me same result. Thats all.

Run both programs in a machine debugger, and compare the x87 floating
point control word register contents. One language/compiler may
truncate; another my round. Usually, the program initialization code
(part of the language runtime) sets the floating point rounding mode.

N. Shamsundar
University of Houston
Sep 16 '05 #7
NM wrote:
In this case, though, it is the same object program. He calls the
subroutine, compiled only once, from a C++ or Fortran main program.
All the calculation is done in the subroutine.

I am not expecting exact result. I know floating points are approximation of
real numbers. What I was expecting was that a subroutine would give me same
output given the same input. In the real world the nontrivial Fortran
subroutine is taking a different path because of the different result and I
did not write it.

Yes. Note that similar differences have been seen for the same
expression at a different line in the same program.

Did not get it. To test if the order was a factor in this case, I used
explicit parenthesis to didctate the order of the expression evaluation. It
did not change anyhthing.

I am not completely sure I understand the way the x87 floating
point processor is initialized, but it might even be possible
to run the same .EXE file and get different results. If the
library doesn't initialize the x87 control register, and the
OS doesn't, you get whatever was there before.

If you want exact results don't use floating point.

I thought that, since I am calling the same implementation from both C++ and
fortran using the same input, it would give me same result. Thats all.

Run both programs in a machine debugger, and compare the x87 floating
point control word register contents. One language/compiler may
truncate; another may round. Usually, the program initialization code
(part of the language runtime) sets the floating point rounding mode.

N. Shamsundar
University of Houston
Sep 16 '05 #8
N. Shamsundar wrote:
NM wrote:
In this case, though, it is the same object program. He calls the
subroutine, compiled only once, from a C++ or Fortran main program.
All the calculation is done in the subroutine.


I am not expecting exact result. I know floating points are
approximation of real numbers. What I was expecting was that a
subroutine would give me same output given the same input. In the real
world the nontrivial Fortran subroutine is taking a different path
because of the different result and I did not write it.

Yes. Note that similar differences have been seen for the same
expression at a different line in the same program.


Did not get it. To test if the order was a factor in this case, I used
explicit parenthesis to didctate the order of the expression
evaluation. It did not change anyhthing.

I am not completely sure I understand the way the x87 floating
point processor is initialized, but it might even be possible
to run the same .EXE file and get different results. If the
library doesn't initialize the x87 control register, and the
OS doesn't, you get whatever was there before.

If you want exact results don't use floating point.

I thought that, since I am calling the same implementation from both
C++ and fortran using the same input, it would give me same result.
Thats all.

Run both programs in a machine debugger, and compare the x87 floating
point control word register contents. One language/compiler may
truncate; another my round. Usually, the program initialization code
(part of the language runtime) sets the floating point rounding mode.

IEEE requires initialization to round-to-nearest, when not otherwise
specified. I don't think the compilers in question can be accused of
violating this. I concur with previous posts about apparent use of a
Fortran compiler which defaults to initialization to 53-bit precision,
vs C compilers which work in 64-bit precision, in order to support long
double. If the same results are wanted regardless of whether main() is
C or Fortran, the compiler flags which (in effect) specify precision
mode should be set explicitly, rather than accepting the differing defaults.
Sep 16 '05 #9

"NM" <nm@nm.com> wrote in message news:dg******** **@news.cs.utex as.edu...

[...]

Never depend on so-called compiler defaults, the undoubted source of your
'irreconcilable ' results. At least with C/C++ you're further ahead than
with Fortran.

--
You're Welcome,
Hrundi
______
"Science is the belief in the ignorance of experts." -- Feynman, in The
Pleasure of Finding Things Out.
Sep 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2585
by: Jeff Hagelberg | last post by:
I'm trying to create a python module which can be used by a python interpreter embedded inside a fortran program I have. To do this, I first created python wrappers for all the functions in my fortran program using f2py. I then start an embedded python interpreter in c code which I link against the fortran program. I invoke the fortran program with a filename containing python code. This file is passed to the c code which passes it on...
15
2087
by: Nick Coghlan | last post by:
Thought some folks here might find this one interesting. No great revelations, just a fairly sensible piece on writing readable code :) The whole article: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=1 The section specifically on white space: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=3 Cheers,
2
1687
by: sunil | last post by:
Hi, We have lot of c and fortran archive libraries that have complex dependencies. We have different server tasks that use some of these libraries. We have developed a tool inhouse that links server tasks by continuously iterating until it figures out the correct library order. Recently we introduced some C++ legacy libraries. I am completely new to C++ linking. Is there some tutorial that can explain the nuances of C++ linking? We do...
2
7245
by: | last post by:
Help! I'm new to c++, and am breaking my teeth on MS Visual C++ (bundled within Visual Studio .NET 2003). Am trying to link simple c++ code to fortran dlls created in Compaq Visual Fortran (v6.1). Posts concerning this topic are common, but none of the posted solutions I've tried work correctly with the above software. The linker can't seem to find the dll (reports 'unresolved external symbol __imp__IMSL_FUN@8'; IMSL_FUN.dll is the f77...
10
2677
by: Julian | last post by:
I get the following error when i try to link a fortran library to a c++ code in .NET 2005. LINK : fatal error LNK1104: cannot open file 'libc.lib' the code was working fine when built using .NET2003. also, when I do not try to link the fortran library (just to see if that was the cause), it builds the exe without any problems. i don't even know how to begin addressing this problem...any help would be
52
5101
by: Nomad.C | last post by:
Hi I've been thinking of learning Fortran as number crunching kinda language for my Physics degree......but then looking around the internet, people are saying that the libraries/ Algorithms once used for number crunching is now slowly converting into C, so do you think I should stick with C, since I know C already, or should I proceed learning fortran?? Any advice?? Thanks
0
3976
by: xieml2007 | last post by:
Dear Madam or Sir, I encountered one problem which is quite similiar to the discussions launched at the web site: http://www.thescripts.com/forum/thread280324.html
9
3690
by: a-lbi | last post by:
I use gcc compiler (version 2.8.1). During linking I get the following error message: Undefined first referenced symbol in file log10l /opt/gcc_4.1.2/solaris10/lib/ libgfortran.a(write.o) strtof /opt/gcc_4.1.2/solaris10/lib/ libgfortran.a(read.o) strtold /opt/gcc_4.1.2/solaris10/lib/
3
2046
by: grspinto | last post by:
Hi there, I am not very used to programming and I am trying to call a Fortran function/subroutine with a C++ main program, but it haven't worked. Untill now, I've been trying to build the easiest program possible, such as c++ calling a c = a + b fortran function. I am trying this on a VS 2005 c++ along with an Intel Visual Fortran. I have been looking for some answers on this forum and I've made these routines: c++-------- #include...
0
8196
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8637
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8504
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4197
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1808
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.