Domanda

I have a program that solves equations and sometimes the solutions x1 and x2 are numbers with a lot of decimal numbers. For example when Δ = 201 (Δ = discriminant) the square root gives me a floating point number.

I need a good approximation of that number because I also have a function that converts it into a fraction. So I thought to do this:

 Result := FormatFloat('0.#####', StrToFloat(solx1)); 

The solx1 is a double. In this way, the number '456,9067896' becomes '456,90679'.

My question is this: if I approximate in this way, the fraction of 456,9067896 will be correct (and the same) if I have 456,90679?

È stato utile?

Soluzione 3

To compare two floating point values with a given precision, just use the SameValue() function from Math unit or its sibbling CompareValue().

if SameValue(456.9067896, 456.90679, 1E-5) then ...

You can specify the precision on which the comparision will take place.

Or you can use a currency value, which has fixed arithmetic precision of 4 digits. So, it won't have rounding issue any more. But you can not do all mathematic computation with it (huge or tiny numbers are not handled properly): its main use is for accounting computations.

You should better never use string representations to compare floats, since it may be very confusing, and do not have good rounding abilities.

Altri suggerimenti

the fraction of 456,9067896 will be correct (and the same) if I have 456,90679?

No, because 0.9067896 is unequal to 0.90679.

But why do you want to round the numbers? Just let them be as they are. Shorten them only for visual representation.

If you are worried about complete correctness of the result, you should not use floating point numbers at all, because floating points are, by definition, a rounding of real numbers. Only the first 5-6 decimal digits of a 32-bit floating point are generally reliable, the following ones are unreliable, due to machine error.

If you want complete precision, you should be using symbolic maths (rational numbers and symbolic representation for irrational/imaginary numbers).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top