Paul Warnick
Paul Warnick

Reputation: 933

If I'm trying to replicate a program in another language. Is it unwise to use more precision?

I'm in the process of converting a program from Scilab code to C++ and it's essential for me to maintain the results produced by Scilab.

I'm aware that Scilab uses IEEE 754 double precision and that C++ doubles (although not required to) are implemented in a similar way.

Is it then a bad idea to use higher precision (e.g. long double) in C++ if I'm trying to exactly match the results of Scilab?

For example: Is it possible for Scilab to calculate a number to be 0.1234 whereas in C++ using long doubles the number would be 0.12345. Thus potentially creating a variance that would result in the two programs producing different results (albeit more accurate in C++).

Upvotes: 0

Views: 69

Answers (1)

Anedar
Anedar

Reputation: 4275

Yes, this is totally possbile.

But since floating point numbers are never totally precise, you should design your algorithm with that in mind and try to avoid that those "rounding errors" screw your calculations after some time.

Even more, as already noted in the comments: Don't expect your C++-program to produce the exact same results as the Scilab program does, especially if it is that critical to small changes. Thats why most numerical simulations are only precise to some limit before they start to produce "wrong" results.

In oder to give you some useful advice, C++ has the very useful option of typedefs. Use a typedef like typedef long double myFloatType and only use myFloatType for your calculations (think of a better name, that actually tells more about what its used for here!). Then you can easily change it afterwards, by just changing one line of code, and compare the results.

If the difference is significant, it might be worth thinking about a better algorithm.

Upvotes: 1

Related Questions