Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fortran Best Practices: Floating Point Numbers comparison #203

Open
band-a-prend opened this issue Nov 11, 2022 · 3 comments
Open

Fortran Best Practices: Floating Point Numbers comparison #203

band-a-prend opened this issue Nov 11, 2022 · 3 comments
Labels
section: learn Relevant for the learn section on the webpage

Comments

@band-a-prend
Copy link
Contributor

The Floating Point Number section of Fortran Best Practices could be extended with 2 subsections:

  1. comparison of two real numbers;
  2. undesirability of using real as iterator within do loops (it was deprecated in Fortran95 standard).

The motivation.
It's common problem for all programming languages when beginner programmer tries to compare fooating points numbers especially using if statement. It would be usefull to demonstrate more accurate approaches (with use of intrinsic procedures?) of comparing numbers to avoid accuracy and computational issues.

The second problem comes from first one and could results in computational issues.

@band-a-prend band-a-prend changed the title Fortran Best Practices: Floating Point Numbers section extension Fortran Best Practices: Floating Point Numbers comparison Nov 21, 2022
@awvwgk awvwgk added the section: learn Relevant for the learn section on the webpage label Dec 13, 2022
@PANKAJ11111111
Copy link

Please give chance i fix this problem

@saikarna913
Copy link

real(dp) :: tol
tol = 10 * epsilon(1.0_dp)

real(dp), parameter :: tol = 1.0e-10_dp
if (abs(x - y) < tol) then
   print *, "Effectively Equal"
else
   print *, "Not Equal"
end if

Floating-point numbers like 0.1 cannot be represented exactly in binary because their binary form is infinite and repeating. Due to the limited precision of floating-point formats (like 32-bit or 64-bit), these numbers are rounded off to fit within the constrained number of bits. This rounding can lead to small errors in representation and calculations. so it is better to add tolerance and check whether the numbers are close enough.

for second
Use integer iterators and convert them to floating point within the loop:

integer :: i
real(dp) :: step, value
step = 0.1_dp
do i = 0, 10
   value = i * step
   print *, value
end do

@saikarna913
Copy link

@band-a-prend do you want me to write this in the documentation website

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
section: learn Relevant for the learn section on the webpage
Projects
None yet
Development

No branches or pull requests

4 participants