Math Round to always upper integer - c#

I need to find a division of two integers and round it to next upper integer
e.g x=7/y=5 = 2; here x and y always greater than 0
This is my current code
int roundValue = x % y > 0? x / y + 1: x / y;
Is there any better way to do this?

You could use Math.Ceiling... but that will require converting to/from double values.
Another alternative is to use Math.DivRem to do both parts at the same time.
public static int DivideRoundingUp(int x, int y)
{
// TODO: Define behaviour for negative numbers
int remainder;
int quotient = Math.DivRem(x, y, out remainder);
return remainder == 0 ? quotient : quotient + 1;
}

Try (int)Math.Ceiling(((double)x) / y)

All solutions looks too hard. For upper value of x/y, use this one
( x + y - 1 ) / y

dunno what's better way or how to define a better way (if in terms of performance you have to run tests to see which will be faster), but here's my solution:
int roundValue = x / y + Convert.ToInt32(x%y>0);
p.s.
still have to deal somehow with neg. numbers... IMO this is the simplest.

+0.5 will aways round to the higher.

Use ceil() function.
It gives the upper value.

It's better to use MidpointRounding from Math.Round
In your case:
Math.Round(value, MidpointRounding.AwayFromZero);
see more: https://learn.microsoft.com/ru-ru/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-double-system-midpointrounding)

Related

Why does Math.Pow(-78.0921, -64.6294) return NaN?

I have two values: X = -78.0921 and Y = -64.6294. Now, when I want to compute Math.Pow(X, Y) it returns NaN. What should I do? How can I solve this problem?
How should I calculate this power? Is there any other function that can calculate this?...or maybe it is not defined mathematically ?
You've tried to compute a number that is not real.
By not real I mean, if we tried every single number between the largest number and the smallest number you can think of, none of those numbers is the solution to -78.0921 to the power of -64.6294.
In fact, no real number is the solution to -1 to the power of 0.5, or the square root of -1, and in general for a^b if a is negative and b is non-integer, the result is not real.
The inability to express such a useful result in real numbers lead to the invention of complex numbers. We say sqrt(-1) = i, the imaginary unit, in the complex number system - all complex numbers have a real component and an imaginary component, expressed as a + b*i.
In general, no negative number to a fractional power produces a real result, as it will have some component of i in it - the closer to a .5 the power is, the more i, the closer to a .0, the more real, and the path follows a circle between real and imaginary, e.g.
-1^x = cos(pi*x)+i*sin(pi*x)
Read more about complex numbers: http://en.wikipedia.org/wiki/Complex_number
If you wish to work with complex numbers in C#, try http://msdn.microsoft.com/en-us/library/system.numerics.complex.aspx
However, unless complex numbers have some meaning in your problem domain (they are meaningful in many electrical engineering, physics and signal analysis problems, for example) it's possible that your data is wrong or your logic is wrong to be attempting to do such a thing in the first place.
The documentation states that the returned value for those inputs is NaN.
x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity: returns NaN
The reason that NaN is returned is that the function is not well-defined for your input values. The Wikipedia article on Exponentiation covers this topic.
I think you mean that it returns NaN because your input matches the following:
x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity
Which is correct, as per the documentation.
Here is what I used for (native C# library System.Numerics):
Complex.Pow(x, y).Real;
The result is the same as:
double checkSquareRoot(double x, double y)
{
var result = Math.Pow(x, y);
if (x > 0)
{
return result;
}
else
{
return -1 * Math.Pow(-x, y);
}
}
Hope it helps!
I had a similar issue and handled as shown below, you have to adjust the min and max values as needed, in my case they are 0 and 10.
double alpha = FastMath.pow(weight, parameters.getAlpha());
if(alpha == Double.NEGATIVE_INFINITY) {
alpha = 0d;
}
if(alpha == Double.POSITIVE_INFINITY) {
alpha = 10d;
}
double beta = FastMath.pow(1d / distanceMatrix[row][column],
parameters.getBeta());
if(beta == Double.NEGATIVE_INFINITY) {
beta = 0d;
}
if(beta == Double.POSITIVE_INFINITY) {
beta = 10d;
}
It is another weak point in C#. We know that cubic root of -125 is equal to -5, but the result of Console.Write(Math.Pow(-125,1.0/3)); is NaN.
Perhaps you should try this:
if (x>0) {
Console.Write(Math.Pow(x,y));
}
else if (x<0) {
double x = Abs(x);
double z = Math.Pow(x,y);
if (y%2==0)
Console.Write(z);
else
Console.Write(-z);
}

1/BigInteger in c#

I want to make
BigInteger.ModPow(1/BigInteger, 2,5);
but 1/BigInteger always return 0, which causes, that the result is 0 too. I tried to look for some BigDecimal class for c# but I have found nothing. Is there any way how to count this even if there is no BigDecimal?
1/a is 0 for |a|>1, since BigIntegers use integer division where the fractional part of a division is ignored. I'm not sure what result you're expecting for this.
I assume you want to modular multiplicative inverse of a modulo m, and not a fractional number. This inverse exists iff a and m are co-prime, i.e. gcd(a, m) = 1.
The linked wikipedia page lists the two standard algorithms for calculating the modular multiplicative inverse:
Extended Euclidean algorithm, which works for arbitrary moduli
It's fast, but has input dependent runtime.
I don't have C# code at hand, but porting the pseudo code from wikipedia should be straight forward.
Using Euler's theorem:
This requires knowledge of φ(m) i.e. you need to know the prime factors of m. It's a popular choice when m is a prime and thus φ(m) = m-1 when it simply becomes . If you need constant runtime and you know φ(m), this is the way to go.
In C# this becomes BigInteger.ModPow(a, phiOfM-1, m)
The overload of the / operator chosen, is the following:
public static BigInteger operator /(
BigInteger dividend,
BigInteger divisor
)
See BigInteger.Division Operator. If the result is between 0 and 1 (which is likely when dividend is 1 as in your case), because the return value is an integer, 0 is returned, as you see.
What are you trying to do with the ModPow method? Do you realize that 2,5 are two arguments, two and five, not "two-point-five"? Is your intention "take square modulo 5"?
If you want floating-point division, you can use:
1.0 / (double)yourBigInt
Note the cast to double. This may lose precision and even "underflow" to zero if yourBigInt is too huge.
For example you need to get d in the next:
3*d = 1 (mod 9167368)
this is equally:
3*d = 1 + k * 9167368, where k = 1, 2, 3, ...
rewrite it:
d = (1 + k * 9167368)/3
Your d must be the integer with the lowest k.
Let's write the formula:
d = (1 + k * fi)/e
public static int MultiplicativeInverse(int e, int fi)
{
double result;
int k = 1;
while (true)
{
result = (1 + (k * fi)) / (double) e;
if ((Math.Round(result, 5) % 1) == 0) //integer
{
return (int)result;
}
else
{
k++;
}
}
}
let's test this code:
Assert.AreEqual(Helper.MultiplicativeInverse(3, 9167368), 6111579); // passed

Round Up a double to int

I have a number ("double") from int/int (such as 10/3).
What's the best way to Approximation by Excess and convert it to int on C#?
Are you asking about System.Math.Ceiling?
Math.Ceiling(0.2) == 1
Math.Ceiling(0.8) == 1
Math.Ceiling(2.6) == 3
Math.Ceiling(-1.4) == -1
int scaled = (int)Math.Ceiling( (double) 10 / 3 ) ;
By "Approximation by Excess", I assume you're trying to "round up" the number of type double. So, #Doug McClean's "ceiling" method works just fine.
Here is a note:
If you start with double x = 0.8; and you do the type conversion by (int)x; you get 0. Or, if you do (int)Math.Round(x); you get 1.
If you start with double y = 0.4; and you do the type conversion by (int)y; you get 0. Or, if you do (int)Math.Round(y); you get 0.
Consider 2.42 , you can say it's 242/100 btw you can simplify it to 121/50 .

Evenly divisible ceiling number

I need some help with some simple math calculation and the most efficient way to execute them in c#.
10 / 4 = 2.5
How do i determine if the sum is a decimal value and if it is I need to round 4 up to 5 so that it divides into 10 evenly.
Any ideas?
I'm assuming that, given some numbers A and B, you want to find a number x, such that:
x evenly divides A
x is greater than or equal to B
x is minimized
in your given example, A = 10, B = 4, and x = 5.
The simplest-to-code way to find x is:
public int getX(int a, int b){
while(a % b != 0){
b++;
}
return b;
}
Generally speaking, it's not easy to find factors of an arbitrary number. In fact, some computer fields, such as cryptography, depend on the fact that factoring big numbers takes a long time.
That sounds extremely vague. You could figure it out using
if (10%4 != 0) ... //checks if there is a remainder
But how to get it up to 5 would need a lot more context.
Here is my suggestion for a short function doing that:
private int FindCeilingDevider(int numberToDivide, int divisor)
{
double result;
do
{
result = (double) numberToDivide / (double) divisor;
divisor++;
}
while (result != Math.Ceiling(result));
return divisor - 1;
}

How to get integer quotient when divide two values in c#?

I want get integer quotient when I divide two values. Per example
X=3
Y=2
Q=X/Y = 1.5 // I want get 1 from results
X=7
Y=2
Q=X/Y=3.5 //I want get only 3 from results
Integer math is going to do this for you.
int x = 3 / 2; // x will be 1
int y = 7 / 2; // y will be 3
int z = 7 % 2; // z will be 1
If you were using decimal or floating-point values in your equations, that would be different. The simplest answer is to cast the result to an int, but there are static Math functions you could also use.
double a = 11d;
double b = 2d;
int c = (int)(a / b); // showing explicit cast, c will be 5
Try Math.Truncate. This should do it.
In VB.NET there is the integer division operator (\). It returns only the integer portion of the division. This comes all the way from the original Dartmouth BASIC so it exists in most forms of BASIC.
try Math.Floor()
There is another elegant way of getting quotient and remainder in .NET using Math.DivRem() method which takes 2 input parameter, 1 output parameter and returns integer.
using System;
For dividend: 7 and divisor: 2
To get only quotient(q)
int q = Math.DivRem(7, 2, _);
//requires C# >= 7.0 to use Discards( _ )
To get quotient(q) and remainder(r)
int q = Math.DivRem(7, 2, out int r);
Math.DivRem() has 2 overloads for 32-bit and 64-bit signed integers.
try using simple maths
int X = 10 ;
int Y = 3 ;
int Q = ( X - ( X % Y ) ) / Y ; // ( it will give you the correct answer )
It works by subtracting the remainder beforehand from the first number so that we don't get a remainder at all !

Categories

Resources