Nearest possible double [duplicate] - c#

This question already has answers here:
Get next smallest Double number
(3 answers)
Closed 8 years ago.
Is there a way to retrieve the successor or the predecessor a certain double? Note that I'm not looking for a "small constant", like double.Epsilon, but for "the smallest positive number that can be added or subtracted from a given value".

You could take binary representation and add one to the fraction part. Example:
using System;
public class Test
{
static void DoubleTest(double value)
{
var binary = BitConverter.DoubleToInt64Bits(value);
binary++;
var newValue = BitConverter.Int64BitsToDouble(binary);
var difference = newValue - value;
Console.WriteLine("value = {0:R}", value);
Console.WriteLine("value' = {0:R}", newValue);
Console.WriteLine("dx = {0:R}", difference);
Console.WriteLine();
}
public static void Main()
{
DoubleTest(0.0000000004);
DoubleTest(4.0000000000);
DoubleTest(4000000000.0);
}
}
prints:
value = 4E-10
value' = 4.0000000000000007E-10
dx = 5.169878828456423E-26
value = 4
value' = 4.0000000000000009
dx = 8.8817841970012523E-16
value = 4000000000
value' = 4000000000.0000005
dx = 4.76837158203125E-07

Related

C# DivideByZeroException won't execute [duplicate]

This question already has answers here:
Divide by zero and no error? [duplicate]
(2 answers)
Why does this method return double.PositiveInfinity not DivideByZeroException?
(4 answers)
Inconsistency in divide-by-zero behavior between different value types
(5 answers)
Closed 2 years ago.
I have written the code below. And I want the output to be :Error!Division by zero..
But my output is: infinity.
What's the problem with this code?
//This is the class:
public class Exc
{
private double number1;
private double number2;
public double result;
public Exc(double n1,double n2)
{
this.number1 = n1;
this.number2 = n2;
}
public void Div(double number1, double number2)
{
try
{
result = number1 / number2;
Console.WriteLine(result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error! Division by zero.{0}",e);
}
}
}
//This is my program:
static void Main(string[] args)
{
Console.WriteLine("Enter the first number:");
double n1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double n2 = Convert.ToDouble(Console.ReadLine());
Exc obj = new Exc(n1, n2);
obj.Div(n1,n2);
Console.ReadKey();
}
Arithmetic operations with the float and double types never throw an exception. The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:
double a = 1.0 / 0.0;
Console.WriteLine(a); // output: Infinity
Console.WriteLine(double.IsInfinity(a)); // output: True
Source
You are going to get divide by zero error only in case of integer input in c#. For double the desired output is infinity. You should put a check for Double.IsInfinity if you want to know if it is divided by zero.

Cannot implicitly convert type 'int' to 'bool' [ [duplicate]

This question already has answers here:
Why can't I use an integer as a condition for a while loop in C#? [closed]
(4 answers)
Closed 5 years ago.
public static bool isValid(int num)
{
bool status = true;
int digit, rev = 0, ck_num; // Added new variable
ck_num = num; // Assigned it to variable num
// Tests for palindrome
while (num)
{
digit = num % 10;
num /= 10;
rev = rev * 10 + digit;
}
if (rev == ck_num) // Checked it against unchanged variable
status = true;
else
status = false;
return status;
}
I've set the public static bool isValid parameter to (int num) but it still says that the type int cannot be converted to bool. Can someone help me with the fix?
In the while loop, you have to provide a condition(bool) so that the loop continues until the condition is met. You have instead provided an int instead of a condition(bool),so while(num) is giving you an error. Just change it to while(num!=0) and that should give you a fix.

how to create int to string like this 50-> "00050" [duplicate]

This question already has answers here:
Convert int (number) to string with leading zeros? (4 digits) [duplicate]
(4 answers)
Closed 5 years ago.
Hello i am trying to process character arrays.
I want to assign the number 50 as string value "00050". How can I do it ?
enter code here
string strRpc(int NumstrRpcSendLen)
{
int digit = Convert.ToInt32( Math.Floor(Math.Log10(NumstrRpcSendLen + 5) + 1));
int len = 0;
char[] d = new char[5];
string result= null;
while (len<5)
{
if (len<digit)
{
d[len] = '0';
}
else
{
}
len++;
}
return result;
}
I'm not sure what your code is doing, but there's a string format specifier for that:
var x = 50.ToString("D5");
//x = "000050"
Look at the documentation for more help
You could try it
var result = 50.ToString("00000");

How do I convert a double to a string of 15 digits?

I have the number 123.1234567890129.
I want the result to be 123.123456789012 without the last digit being rounded.
I've tried:
("123.1234567890129").ToString("G15") //123.123456789013
One way that you could do this is to round to 16 like this
("123.1234567890129").ToString("G16").Substring(0, 16);
Since you said double.
Since doubles can have ANY number of digits you must round in some way. (you either round down, as inferred or you round up as in practice for this case)
Since you imply you only want to see the number of precise digits, you must find out how many digits are on each side of the decimal point (0 to 15 on either side)
An extenstion to round down
public static class DoubleExtensions
{
public static double RoundDown(this double value, int numDigits)
{
double factoral = Math.Pow(10, numDigits);
return Math.Truncate(value * factoral) / factoral;
}
}
test case
const int totalDigits = 15;
// why start with a string??
string somestring = "123.1234567890129";
const int totalDigits = 15;
// since the title says 'convert a double to a string' lets make it a double eh?
double d = double.Parse(somestring);
int value = (int)d;
double digitsRight = d - value;
int numLeft = (d - digitsRight).ToString().Count();
int numRight = totalDigits - numLeft;
double truncated = d.RoundDown(numRight);
string s = truncated.ToString("g15");
You can create custom FormatProvider and then create your implementation.
class Program
{
static void Main(string[] args)
{
double number = 123.1234567890129;
var result = string.Format(new CustomFormatProvider(15), "{0}", number);
}
}
public class CustomFormatProvider : IFormatProvider, ICustomFormatter
{
private readonly int _numberOfDigits;
public CustomFormatProvider(int numberOfDigits)
{
_numberOfDigits = numberOfDigits;
}
public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? this : null;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!Equals(formatProvider))
return null;
if (!(arg is double))
{
return null;
}
var input = ((double)arg).ToString("R");
return input.Length > _numberOfDigits + 1 ? input.Substring(0, _numberOfDigits + 1) : input; // +1 because of dot
}
Unfortunately you cannot do in this way:
var result = number.ToString(new CustomFormatProvider(15));
because of value types limitation.. Double supports only CultureInfo and NumberFormatInfo formatters. If you pass different formatter it will return default instance: NumberFormatInfo.CurrentInfo'. You can make small workaround by usingstring.Format` method.
New to the community. First answer here. :)
I think you are looking for something like this. Works with or without decimal. This will cut the digits after the 15th digit only irrespective of length of the number. You can get the user to decide the accuracy by getting the precision value as a user input and performing that condition check accordingly. I used 15 because you mentioned it. Let me know if it works for you. Cheers!
string newstr;
int strlength,substrval;
double number;
string strnum = "123.1234567890129";
strlength = strnum.Length;
if(strlength>15)
{
strlength = 15;
}
substrval = strlength;
foreach(char x in strnum)
{
if(x=='.')
{
substrval++;
}
}
newstr = strnum.Substring(0, substrval);
number=Convert.ToDouble(newstr);
Alife Goodacre, code is printing "123.12345678901" insted "123.123456789012"
there should be Substring(0, 16) insted of Substring(0, 15)
Convert.ToDouble("123.1234567890129").ToString("G16").Substring(0, 16)
OutPut Screen with Code.

Multiplying Different Data Types in an Array in C#

I am receiving an error "Operator '*' cannot be applied to operands of type 'int' and 'decimal[]'", as I am attempting to multiply two values with different data types (one being a value located in an array). My question is how am I able to multiple numberOfMinutes * perMinuteRate in my code below? My variable is called total, which I declared a double data type (although may be incorrect).
I tried changing data types and played with formatting (like ToString), but I am not sure what to do. I also tried to google the answer with no success.
I am by no means a professional programmer; I'm not in school. I'm a data analyst who is learning to program.
Here is my code:
static void Main(string[] args)
{
int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
decimal[] perMinuteRate = { .07m, .1m, .05m, .16m, .24m, .14m };
int numberOfMinutes;
int userAreaCode;
string inputString = "1";
while (inputString != "0")
{
int x;
Console.WriteLine("Enter the area code for your call (or 1 to end):");
inputString = Console.ReadLine();
userAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("How many minutes will your call last?");
inputString = Console.ReadLine();
numberOfMinutes = Convert.ToInt32(inputString);
for (x = 0; x < areaCodes.Length; x++)
{
if (userAreaCode == areaCodes[x])
{
***double total = numberOfMinutes * perMinuteRate;***
Console.WriteLine("You call to {0} will cost {1} per minute for a total of {2}.", areaCodes[x], perMinuteRate[x].ToString("C"), total.ToString("C"));
x = areaCodes.Length;
}
}
if (x != areaCodes.Length)
{
Console.WriteLine("I'm sorry; we don't cover that area.");
inputString = "1";
}
else
{
Console.WriteLine("Thanks for being our customer.");
inputString = "0";
}
Console.ReadLine();
}
}
Thank you in advance.
Change:
double total = numberOfMinutes * perMinuteRate;
to
double total = (double)(numberOfMinutes * perMinuteRate[x]);
The same way you index into perMinuteRate in the line directly below.
The expression [int] * [decimal] will result in a decimal, and the cast (double) will convert it to a double
To avoid loss of precision, change it to:
decimal total = numberOfMinutes * perMinuteRate[x];

Categories

Resources