Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can functions like sin() be redefined, in Fortran, C or Java?

Can a mathematical function like sin() be redefined, in Fortran, C or Java code, while preserving the default behavior of other mathematical functions like cos()? Or can another function named sin() but that accepts different argument types be defined in addition to the built-in sin()? I am interested in general features of these languages (I am thinking of applications like the implementation of non-usual number algebras).

I tried to define a sin() function in a Fortran 95 program, but the intrinsic sin() function was called instead… Is there a way around this? what about C and Java?

PS: Here is an example of application: you have some calculation code already written; you realize that it would be useful if all the calculations could yield numbers with uncertainties (like 3.14±0.01). It would be convenient to keep all mathematical expressions (like for instance z = sin(x+2*y)) unmodified in the code, even if x and y are numbers with uncertainties (instead of floats). This is an exemple of why having a sin() function that generalizes the usual sine function is useful.

The reason why I also included in the question the condition that certain functions be not modified is that a custom library that calculates the uncertainty on sin(x) when x has an uncertainty might not implement all the standard functions, so it would be nice to still be able to have access to some standard functions.

These features are present in Python, and this makes using the uncertainties Python module (which I wrote) quite convenient. I would be interested to know better how much of this convenience is due to Python being the language it is, and how convenient a similar uncertainty calculation library written for C, Fortran or Java could be.

like image 768
Eric O Lebigot Avatar asked Dec 03 '22 00:12

Eric O Lebigot


1 Answers

There is no problem redefining an intrinsic in Fortran. This won't effect other intrinsics, but of course you won't have access to the intrisic that you have "shadowed". Example code:

module my_subs

contains

function sin (x)
real :: sin
real, intent (in) :: x

sin = x**2

return
end function sin

end module my_subs

program test_sin

use my_subs

implicit none

write (*, *) sin (2.0)

stop

end program test_sin

Output is 4.0

gfortran gives a warning: "'sin' declared at (1) may shadow the intrinsic of the same name. In order to call the intrinsic, explicit INTRINSIC declarations may be required." ifort does not give a warning..

like image 197
M. S. B. Avatar answered Dec 04 '22 14:12

M. S. B.