Search code examples
c#mathalgebrafloor

Can anyone Solve for x with c#? floor(x * 1.04) = 258


I'm adding the floor of 4% to an int in this example 249. It will be a different int every time though. here is my code for that which works fine.

int qty = 249;
qty += Convert.ToInt32(Math.Floor((double)qty * 0.04));

but the problem that comes up is after this sometime later in the program and after I no longer have the original value I need to revert back to the old value using the new value. I cant just subtract 4% because although it works sometimes a lot of the time it is inaccurate. The closest I came to is this

double d = Math.Round((double)qty * 0.036);
qty = Convert.ToInt32((double)qty - d);

which is accurate most of the time with smaller numbers, but not all the time. I did come up with an equation that should work if I could solve for x and get a whole number but so far I am stumped on how to solve for x. Here is the equation I came up with solve for x, floor(x*1.04) = 258 . Can anyone solve that and have it give me a whole number or does anyone have a better idea on how to do this without storing the old value anywhere? I am well aware that I could store the old value but if it is easily reversible with a simple math problem then I see no reason to store it. Also this will be done on a large list of items so it wouldn't just be storing one original value it would be thousands.


Solution

  • This comment from @MarkDickinson was the answer I was looking for:

    The mapping is injective, so it is reversible. Mathematically, you can always recover the original quantity by using floor((qty + 1.0) / 1.04). Numerically, it's possible that there are some corner cases that might cause issues, but I didn't discover any for qty up to 10**6.