Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Weird fortran problem (Assigned variable value doesn't match up with output)

  1. May 23, 2012 #1
    I ran into a kind of strange thing today while coding. I needed Pi in a program, so I used 2*accos(0.0) to pull it out, but my answers were slightly off. I checked the Pi calculated and it was off after a few decimal places.

    "Odd", I thought, and just decided to put in Pi as an assigned number. However, this still didn't solve the problem! No matter how I inputted it, it was being altered somehow by the program. I whipped up a really quick program to demonstrate what I'm talking about.

    program probs


    if you check the output( assuming it's not just my machine or compiler for some reason) you'll see the values for v and the number inputted for it are not the same.

    I'm guessing it has something to do with using the kind flag, but I'm not much of a comp sci person, and my searches didn't turn up anything useful.

    Anyone have any clue how to fix this? If it is related to kind, how can I keep high precision while avoiding this problem?
  2. jcsd
  3. May 23, 2012 #2
    The reason being the value you are assigning is one type and the variable on the left is a different type....if you are going to be declaring variables of different types that the default, you need to assign value of different type than the default; in fact, they should be declared of the exact same type...follow? maybe an example:

    Code (Text):

    program probs
    integer, parameter :: rrr=SELECTED_REAL_KIND(15,307)
    real(KIND=rrr) :: v

    Here, we first declare a "type"...that's the integer variable rrr.
    Then, we declare the variable v of that kind
    Then, in order to assign a literal constant to that variable with suffix it with the same "type"...with '_rrr'

    Now, test this program and you will see.
  4. May 24, 2012 #3


    User Avatar
    Science Advisor
    Homework Helper

    Or, the "traditional" way is to make sure your constants are double precision.

    accos(0.0) will use the single precision version of the function because its argument is single precision, so the result will only be accurate to about 5 decimal places. acos(0.0d0) should be accurate to about 15 places.
  5. May 24, 2012 #4
    Thanks guys! I was just kind of confused because the output of the variables of real(kind=8) goes to the correct amount of decimal places. I never really thought it through to declare my assigned values as some type, I just assumed it would assign whatever value I placed there the correct type. It's working now tho
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook