Bad Dub
Bad Dub

Reputation: 1593

Trying to Convert Excel Equation to C#

I've got this Excel equation and I'm struggling to convert it into c#.

The "to the power of" and "log" parts are tripping me up.

The excel equation is as follows:

LOG((10^(PreSkillRating/400)/((-ChangeInRating/KFactor)+1)-10^(PreSkillRating/400)))*400/LOG(10)

So far I have this:

Math.Log((Math.Pow(PreSkillRating / 400, 10)) / (((ChangeInRating * -1) / KFactor) + 1) - Math.Pow((PreSkillRating / 400), 10)) * 400 / Math.Log(10)

I'm also aware that I will have to check for 0 when dividing to stop the Attempted to divide by zero error.

For example when I use the following values for each of the variables I get 1879.588002 as the answer in excel but infinity in c#.

PreSkillRating = 1600
ChangeInRating = 50
KFactor = 60

What am I doing wrong?

Upvotes: 2

Views: 310

Answers (2)

Christoph Bimminger
Christoph Bimminger

Reputation: 1018

Based on earler comments and my first answer, let's summarize:

  • typecast for double division
  • wrong order of arguments for Pow
  • wrong method Math.Log(x). You can use Math.Log(x,10) or Math.Log10(x)

Try following implementation:

Math.Log10((Math.Pow(10, (double)PreSkillRating / 400)) / (((ChangeInRating * -1.0) / KFactor) + 1) - Math.Pow(10, (double)PreSkillRating / 400)) * 400 / Math.Log10(10)

Upvotes: 4

Christoph Bimminger
Christoph Bimminger

Reputation: 1018

Are your variables int values? Then you have to add a typecast. See Division in C# to get exact value

Otherwise, divisions are performed as integer divisions, which causes rounding operation for each step separately.

Upvotes: 1

Related Questions