Skip to content

SFR2: Allow numpy to format floats#313

Merged
christianlangevin merged 5 commits into
modflowpy:developfrom
mwtoews:sfr-mods2
Apr 2, 2018
Merged

SFR2: Allow numpy to format floats#313
christianlangevin merged 5 commits into
modflowpy:developfrom
mwtoews:sfr-mods2

Conversation

@mwtoews
Copy link
Copy Markdown
Contributor

@mwtoews mwtoews commented Apr 2, 2018

This fix is related to #300, where flopy's mfsfr2.write_file method adds superfluous digits to output files.

The issue seems to be with how Python's str.format interacts with Numpy. For instance, with two examples:

import numpy as np
x = np.float32(101.1)
print('{}'.format(x))  # 101.0999984741211
print('{!s}'.format(x))  # 101.1

With the first print example, numpy's float32 is converted to Python's native float, which is a double precision value that is formatted by Python as a native float. It is equivalent to print('{}'.format(float(x))) with lousy output. This is the same behaviour with Python 2 and 3.

With the second print example, numpy returns a string representation of the float32 type, retaining the correct precision. This PR implements the second method to let numpy format the value to a str. The example described in #300 is formatted nicer as:

# SFR package for  MODFLOW-2005, generated by Flopy.
4 2 0 0 86400.00000000 0.00010000 0 0 
1 1 1 0 0 101.1
1 1 1 0 0 202.2
1 1 1 0 0 103.4
1 1 1 0 0 193.2
2 0 0
0 0 0 0 543.4 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 987.6 0 0 0 
0 0 0 0 0 
0 0 0 0 0 

Is there any performance difference? Not really:

$ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> import numpy as np
>>> timeit.timeit("'{}'.format(x)", "import numpy as np; x = np.float32(101.1)", number=100000)
0.1474021040048683
>>> timeit.timeit("'{!s}'.format(x)", "import numpy as np; x = np.float32(101.1)", number=100000)
0.15334038599394262

@coveralls
Copy link
Copy Markdown

coveralls commented Apr 2, 2018

Coverage Status

Coverage decreased (-1.8%) to 69.468% when pulling c3eb9e2 on mwtoews:sfr-mods2 into 05a9caf on modflowpy:develop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants