user2960398
user2960398

Reputation: 383

Getting different output from Math.Sqrt in C#

I have interesting issue with Math.Sqrt in C#. I am getting different output in one application (different place in application) from Math.Sqrt.

I have big project and application have lot of mathematics calculation.

Story

Animation Irrlich dll is use in the application Code:

private void Win_Load(object sender, EventArgs e)
  {
 double myOutput = Math.Sqrt(2.0); //1.4142135623730951
 IrrlichtCreationParameters creationParameter = new IrrlichtCreationParameters();
 creationParameter.DriverType = IrrlichtLime.Video.DriverType.Direct3D9;
 IrrlichtDevice.CreateDevice(creationParameter);
 myOutput = Math.Sqrt(2.0);//1.4142135381698608
}

I want to output 1.4142135623730951 every time.

Anyone have any idea, Why got different output after use IrrlichtLime.Video.DriverType.Direct3D9?

On which cases we got output different from Math.sqrt?

Upvotes: 1

Views: 448

Answers (2)

Steve Cooper
Steve Cooper

Reputation: 21480

You don't say what the 'wrong' result is, but be aware that mathematical operations like SQRT will always have some rounding error. That means that you should not directly compare doubles, but make sure they are close to within some tolerance;

const double delta = 0.00000001d;
bool same = Math.Abs(d1 - d2) < delta;

So if you get nearly the same answer, this is about the best you can get from double-precision numbers.

Upvotes: 0

Zein Makki
Zein Makki

Reputation: 30022

You have inconsistent usage of types (eventhough i don't see your code) but here is the proof :

double v1 = Math.Sqrt(2.0); // 1.4142135623730951
double v2 = (float)Math.Sqrt(2.0);  // 1.4142135381698608

You need to use the same type everywhere and do not do any casting or you might lose some precision.

It seems that you're doing a lot of calculations before you have the value 2.0 (it it maybe ≃ 2.0) . Double can't represent all numbers precisely, if you need precision then you have to use Decimal.

Upvotes: 7

Related Questions