Update string format representation used in instrument file output #70
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background
When a parameter needs to be written into a
McStas
/McXtrace
.instr
fileMcStasScript
makes use ofprintf
-style format specifiers, notably%d
,%s
, and%G
.Importantly, the last is used for floating point values which seems reasonable since, quoting the Wikipedia entry for
%g
/%G
Problem
Unfortunately in some cases this style of string formatting can lead to truncation for floating point values, e.g.,
where the last digit has been truncated and the resulting string representation is rounded up.
This behaviour led to the discovery of a bug in
Elliptic_guide_gravity.comp
where the lengths of a number of guide segments were written byMcStasScript
into aDECLARE
array and their total length was written byMcStasScript
as a component parameter. Truncation of both the individual element lengths and their total length produced aC
instrument file where the sum of the segment lengths and the input total length were no longer in agreement.Solution
This PR corrects this problem by moving to
f
-string formatting and dropping the format specifier forstr
andfloat
values, since Python does a good job of accurately representing values viastr()
already.For example, the value above is no longer truncated
and this works for numbers with large-magnitude exponents as well
Side effects
A benefit of
f
-strings in Python is that the resulting code is easier to read, with the position of values directly related to their position in the resulting string.For example,
or