Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

System.Math problem


  • Please log in to reply
2 replies to this topic

#1 PawleysPlayr

PawleysPlayr

    Member

  • Members
  • PipPip
  • 11 posts

Posted 01 June 2011 - 04:33 PM

I'm probably doing something utterly stupid. Using the micro framework... The System.Math.ABS will only take a type int...it seems to have only that one overload. Same with System.Math.Round... will take a double, but not a second parameter to specify the number of places to round to. Anyone else seen this?

#2 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 02 June 2011 - 07:05 AM

The math is something that the MF guys decided to cut enough (IMHO).
Integers are obviously limited for the math, but doubles are too heavy for the MF.
I suggest to use floats unless strictly necessary.

The Abs is straightforward:

public static float Abs(float value)
{
  return (value >= 0) ? value : -value;
}
To round a value by a certain number of decimals, you may use this function:

private static float[] PowersOfTen = new float[]
{
  1.0f,
  10.0f,
  100.0f,
  1000.0f,
  10000.0f,
  100000.0f,
  1000000.0f,
  // etc.
}

public static float Round(float value, int digits)
{
  var power = PowersOfTen[digits];
  return power * (long)(value / power);
}
NOTE: I used an explicit cast to a long, because it does exactly what I need and it is very fast. However a long is much limited in range respect to a float.

Cheers
Biggest fault of Netduino? It runs by electricity.

#3 PawleysPlayr

PawleysPlayr

    Member

  • Members
  • PipPip
  • 11 posts

Posted 02 June 2011 - 11:39 AM

Thanks Mario!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.