Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Given a string "3°5'2''" I need to convert it to a decimal representation.
The first step, obviously, is to convert your string notation to degrees, minutes, and seconds. That's simple string-parsing, so I'll leave that as an exercise.
Let's say you're going to use a Tuple for this (http://msdn.microsoft.com/en-us/library/system.tuple.aspx).
public static double GetDegreesFromDMS(Tuple<double,double,double> dms)
{
// First, calculate total seconds.
double seconds = (dms.Item2 * 60) + dms.Item3;
// This makes the fraction of a degree this number / 3600
return dms.Item1 + (seconds / 3600);
}
To call this, you would construct a Tuple with the DMS values like so:
var dms = new Tuple<double, double, double>(3, 5, 2);
var degrees = GetDegreesFromDMS(dms);
Good luck.
For the math portion, I will use the answer from https://stackoverflow.com/a/3249890/1783619 You could of course write your own implementation. I would create my own "Degree" class that looks like this:
public class Degree
{
int degrees;
int minutes;
int seconds;
public static Degree Parse(string input)
{
//Implementation below
}
public decimal ToDecimal()
{
// From https://stackoverflow.com/a/3249890/1783619
// Modified to use floating point division since my inputs are ints.
//Decimal degrees =
// whole number of degrees,
// plus minutes divided by 60,
// plus seconds divided by 3600
return degrees + (minutes/60f) + (seconds/3600f);
}
}
In the parse function, I would split the string based on the well known delimiters and assign the class members based on the split string. Note that this function isn't very safe for bad input as is:
public static Degree Parse(string input)
{
Degree parsedDegree = new Degree();
string[] seperatedStrings = input.Split(new char[] {'°', '\''});
parsedDegree.degrees = seperatedStrings[0];
parsedDegree.minutes = seperatedStrings[1];
parsedDegree.seconds = seperatedStrings[2];
return parsedDegree;
}
To use it:
Degree myDegree = Degree.Parse("3°5'2''");
Decimal myDecimal = myDegree.ToDecimal();
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I need a method to return the firsts non zero numbers from a double in the following way: Any number >= 1 or == 0 will return the same; All the rest will return as per the following examples:
(Please note that I am using double because the potential imprecision is irrelevant in the use case whereas saving memory is relevant).
double NumberA = 123.2; // Returns 123.2
double NumberB = 1.2; // Returns 1.2
double NumberC = 0.000034; // Returns 3.4
double NumberD = 0.3; // Returns 3.0
double NumberE = -0.00000087; // Returns -8.7
One option would be to iteratively multiply by 10 until you get a number greater than 1:
public double RemoveLeadingZeros(double num)
{
if (num == 0) return 0;
while(Math.Abs(num) < 1) { num *= 10};
return num;
}
a more direct, but less intuitive, way using logarithms:
public double RemoveLeadingZeros(double num)
{
if (num == 0) return 0;
if (Math.Abs(num) < 1) {
double pow = Math.Floor(Math.Log10(num));
double scale = Math.Pow(10, -pow);
num = num * scale;
}
return num;
}
it's the same idea, but multiplying by a power of 10 rather then multiplying several times.
Note that double arithmetic is not always precise; you may end up with something like 3.40000000001 or 3.3999999999. If you want consistent decimal representation then you can use decimal instead, or string manipulation.
I would start with converting to a string. Something like this:
string doubleString = NumberC.ToString();
I don't know exactly what this will output, you will have to check. But if for example it is "0.000034" you can easily manipulate the string to meet your needs.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I've got a project I'm working on. This is the only error I have:
Cannot implicitly convert type 'float' to 'int'.
I understand somewhat what that means. I just need help converting my float to int.
This is just an example of one of the floats:
float key = 0.5f;
int key = 53;
Here's the specific code section:
// price in scrap, e.g. 29 / 9 = 3.33 ref
static int BuyPricePerTOD = 21;
// price in scrap, e.g. 31 / 9 = 3.55 ref
static float SellPricePerTOD = BuyPricePerTOD + 0.5F;
static int BuyPricePerKey = 53;
static float SellPricePerKey = BuyPricePerKey + 0.5F;
static int TimerInterval = 170000;
static int InviteTimerInterval = 2000;
int UserWeapAdded,UserScrapAdded,UserRecAdded,UserRefAdded,
UserKeysAdded,UserTODAdded,BotTODsAdded,BotKeysAdded,
BotScrapAdded,BotRecAdded,BotRefAdded,InventoryMetal,
InventoryScrap,InventoryRec,InventoryRef,InventoryKeys,
InventoryTOD,PreviousTODs,PreviousKeys,WhileLoop,InvalidItem = 0;
float UserMetalAdded, BotMetalAdded, OverpayNumKeys,
OverpayNumTOD, ExcessInScrapKey, ExcessInScrapTOD = 0.0F;
double ExcessRefinedKey, ExcessRefinedTOD = 0.0;
Firstly, there are integers and floating-point numbers. Integers are always whole numbers, such as 0, 1, -32, 42 and 1337. On the other hand, floating-point numbers can have a fractional part: 0, 1, -32.1, 42.7 and 123.456788 are all valid floating-point numbers.
When converting between integers (int) and floating-point (float) numbers, you can do this:
int someInt = 42;
float someFloat = someInt; // 42.0f
But you can't do this:
float someFloat = 42.7f;
int someInt = someFloat; // ?
The reason the first conversion is possible, is that converting the integer number (int) to a floating-point number (float) does not change the number. It is a safe conversion, and therefore can be done implicitly.
The reason the second conversion is not allowed, is that converting the floating-point number (which may have a fractional part) to an integer number (that never has a fractional part) must drop the fractional part of the number, i.e. it becomes a different number. This is not safe, and can therefore only be done explicitly.
To explicitly convert one type of number to another, you use a cast. That's the parentheses before the number with the type of the number that you want to convert it to.
float someFloat = 42.7f;
int someInt = (int)someFloat; // 42
Note that the fractional part of the floating-point number was dropped. It's as if it has been rounded towards zero. If you want to round the floating-point number to the nearest whole number, use the Math.Round method.
float someFloat = 42.7f;
int someInt = (int)Math.Round(someFloat); // 43
Try this :
int numInt = (int)Math.Ceiling(numFloat);
msdn documentation
You may want Math.Round() or Math.Floor() by the way.
Example :
float numFloat = 1.5f;
int testCeiling = (int)Math.Ceiling(numFloat);
int testFloor = (int)Math.Floor(numFloat);
int testRound = (int)Math.Round(numFloat);
Console.WriteLine("testCeiling = {0}", testCeiling.ToString());
Console.WriteLine("testFloor = {0}", testFloor.ToString());
Console.WriteLine("testRound= {0}", testRound.ToString());
output :
testCeiling = 2
testFloor = 1
testRound= 2
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I need to calculate 2^N, however N can be as large as 1929238932899 and I'm stuck using a long data type which can't hold a number that large.
I've currently tried converting to 'BigInt' however I'm still stuck with the long data type restriction from what I've seen as well.
I have a function which calculates the power. However, with the long data type, it just returns 0 when the number gets too big. Note that this is just a generic recursive power function.
For example, with 2^6 its meant to return 64 and with 2^47 to return 140737488355328. However, when it becomes 2^8489289, it just returns 0.
To represent 2^N in binary form, you need N+1 bits (binary digits), that is
(1 929 439 432 949 324 + 1) / 8 = 241 179 929 118 665.6 bytes ~ 219 PiB for a single number, if you really want to work with it.
Or you can just write down 2^N in binary form: 1 followed by N zeroes.
Since 2^N is an integer, you can represented it using Integer factorization.
You can put that in a class like this:
class FactorizedInteger {
private Dictionary<long, long> _factors = new Dictionary<long, long>();
public FactorizedInteger(long radix, long exponent) {
_factors[radix] = exponent;
}
public void Add(FactorizedInteger other) {
foreach(var factor in other._factors) {
if (_factors.ContainsKey(factor.Key)) {
_factors[factor.Key] += factor.Value;
} else {
_factors[factor.Key] = factor.Value;
}
}
}
public override string ToString() {
return "(" + String.Join(" + ", _factors.Select(p => $"{p.Key}^{p.Value}")) + ")";
}
}
As you can see, you can even add some mathematical operations without exhausting the memory of the computer. I've included Add as an example.
To use it:
var e1 = new FactorizedInteger(2, 1929238932899);
var e2 = new FactorizedInteger(2, 64);
Console.WriteLine(e1);
e1.Add(e2);
Console.WriteLine(e1);
Output:
(2^1929238932899)
(2^1929238932963)
This example needs to be made much smarter to be really usefull, but it is a possible representation of such large numbers.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need someone to give me an idea on how to go on about this problem.Using a loop to calculate the fraction , There is no common value.I want to get the sum
Eg for fraction :
1 1/5 1/10 1/15 1/20 … 1/290 1/295 1/300
code snippet:-
int sum=0;
for(int i=1;i<=60 ;i++)
{
int sum=1
}
These sort of problems are actually surprisingly non-trivial due to issues with working with floating point, and decimal types for that matter.
Accepting that you want a loop solution for this (a closed form solution for n terms does exist), first note that your series can be written as
1 + 1/5(1 + 1/2 + 1/3 + ... + 1/60)
Then note that a good rule of thumb when working with floating point types is to add the small terms first.
So an algorithm would be of the form
double sum = 0.0;
for (int i = 60; i >= 1; --i){
sum += 1.0 / i;
}
sum = sum / 5 + 1;
Note the 1.0 in the numerator; that's there to defeat integer division.
Reference: Is floating point math broken?
͏Since you asked for a hint:
float sum = 1.0;
for (int i = 5; i <= ??; i += ??) {
sum += 1.0/i;
}
What goes in place of the ??s?
try this code:
double sum=1;
for(int i=5; i<=300; i+=5)
sum += (double) 1 / i;
The value of sum will be 1.93597408259035
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How can I find how many indivisible units of 1,000 are needed to overshadow a random number?
For example, for random number 5,123 I'm going to need 6 x 1,000 to overshadow it, so: MyAlgorithm(5123, 1000) = 6
Edit1: I am sorry if despite my endeavor to articulate my problem into a meaningful description my dyslexia took over, I hope this edit makes it a bit more comprehensible.
Well, if I understand your question, it sounds like you could simply convert the parameters to decimals, divide, then use Math.Ceiling:
int output = (int)Math.Ceiling((decimal)5123 / (decimal)1000); // 6
Alternatively, you could avoid the conversions and rely purely on integer division and the % operator (modulus), like this:
int output = (5123 / 1000) + (5123 % 1000 == 0 ? 0 : 1);
If you want this in a method simply wrap it up like this:
static int MyAlgorithm(int a, int b)
{
return (a / b) + (a % b == 0 ? 0 : 1);
}
if I've understood you correctly, this is really just a one-liner:
public static int MyAlgorithm(int input, int units)
{
return input%units == 0 ? input/units : input/units + 1;
}
the only case when it isn't simply the result of input/units + 1 is the case when there is no remainder
public int MyAlgorithm(int x, int y)
{
int result = x / y;
return (result < 0) ? (result - 1): (result + 1);
}