2

Let's say I have a set of float numbers, each with an int value of Significant Figures.

What is the simplest and fastest C# method to find the minimum significant step (as a power of 10) for each value?

Value Significant Figures Expected Result
1.0123 3 0.01
1.0123 4 0.001
4525 2 100
0.007589 1 0.001
42 1 10

*In bold it's marked the Significant Figures of each Value.

I am tempted to use Math.Log10() somehow, but I cannot yet figure out how.

Miguel
  • 143
  • 1
  • 7
  • 1
    Floating point types aren't stored like that. In fact, even `0.3` can't be stored exactly. Someone even created the site `https://0.30000000000000004.com/` which comes up first in Google results for `0.3` because ... it's an exact match of what the float `0.3` translates to – Panagiotis Kanavos Jul 20 '23 at 18:04
  • Do you think that could affect in any way my goal? I don't see it clearly.. Nevertheless, number types could be changed and decimal could be used. Or other "more precise" type – Miguel Jul 20 '23 at 18:10

1 Answers1

3

One solution:

static float MinimumSignificantStep(float number, int significantFigures)
    => (float)Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(number))) - significantFigures + 1);

I wouldn't be surprised if there were much faster solutions out there.

Keep in mind floating points numbers can be surprising because they're stored as binary numbers multiplied by a power of two, which doesn't always match up nicely with the powers of 10 we usually use. So expect 0.999999, 0.0001 or similar numbers close to the edges to end up with a "wrong" number of digits.

relatively_random
  • 4,505
  • 1
  • 26
  • 48
  • I think you got it right, thanks! Anyways, in order to avoid negative values throwing `NaN` for the logarithm, I would change `number` for `Math.Abs(number)`. If you edit it with the correction I will accept your answer – Miguel Jul 20 '23 at 18:42
  • @Miguel You're right, fixed. – relatively_random Jul 21 '23 at 07:07