Menu
  • HOME
  • TAGS

Value of variable as integer and as double

c++,c,integer,double

Q is 4241297856 (double)Q has 64-bit IEEE-754 representation 0x41EF99A238000000 In little-endian, the lower 4 bytes of this occupy the same space as (int)Q would. 0x38000000 is 939524096 Handy online converter: http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html...

Calculating time for any sum to double, at a given rate of interest compounded annually

c++,while-loop,int,double

interest is an int so this line interest / 100 is doing integer division, and will always be 0. The quick fix would be to change the literal so you are doing floating point math sum += sum*(interest / 100.0); ...

Double error message with remote data annotation mvc 5

asp.net-mvc,double,data-annotations

I just fixed the problem i just removed the remote annotation on the lastName, the functionality is still the same but the second error was removed. I thought i had to add the same annotation on the second field to be validated too.

Ruby CSV gem returning Infinity instead of double

ruby,postgresql,csv,double,infinity

First of all, Postgres can probably handle loading CSVs without Ruby's help. As for your question... CSV does not define data types, so whenever you read CSV data into something that expects data types (like Excel or Ruby) the program has to guess. When Excel sees 20150519E000010 it is guessing...

1. / this.norm(); Is `1.` just syntactic sugar?

java,double

It's one of the many ways of specifying a double literal, without it 1 would be an integer, which would mean you'd be doing integer division, not double division... System.out.println(1 / 3); // ==> 0 <== Uh oh, integer division System.out.println(1. / 3); // ==> 0.333333 System.out.println(1.0 / 3); //...

PHP function to determine if a variable is a number(not hex or other numericals that have letters in them)

php,double,numeric

There's no built in function that I know of. A regular expression can catch it pretty easy, ^\d+(\.\d*)?$ (will match '0.123', but not '.123'). But here's another alternative strategy. <?php function isDigit($var) { return ((string)$var == (float)$var); } var_export(isDigit('123.3')); // true var_export(isDigit('-321')); // true var_export(isDigit('0xFFF')); // false UPDATE: I just...

Using float and double for calculation, giving different results [duplicate]

java,floating-point,double

Because of how floats and decimals are represented, the casts could be causing different results. For: double value1 = 0.999939f * 0.987792f you are multiplying two floats and then casting it to a double. The resulting float representation is the one being converted to a double. For: double value2 =...

PostgreSQL - get all integer digits from double precision field for use in to_char function

postgresql,double,precision,numeric,to-char

The reason is that for the purpose of the equality comparison, the type with the higher resolution is cast to the type of the lower resolution. I.e.: in the example the numeric is cast to double precision. Demo: SELECT * , num = dp AS no_cast , num::float8 = dp...

Java double comparing vs. String comparing

java,compare,double

The class Double provides a compare method that treats NaNs as being equal. I have tested several of the interesting cases, and in each case it gave the same result as the more indirect String method: public class Test { public static void main(String[] args) { testit(0.0,0.0); testit(0.0, -0.0); testit(Double.NaN,...

>= not working, R [duplicate]

r,if-statement,double,logic

There is nothing wrong with the >=, your problem is that 1 is not really one. Try this Ax >= 1 [1] FALSE Ax == 1 [1] FALSE and format(Ax, digits = 20) [1] "0.99999999999999977796" Edit: A possible Solution As solutions to your problems you can return the final result...

Using mmap to allocate double 2D array

c,arrays,double,mmap

If N is a compile-time constant or if your compiler supports variable length arrays (VLAs), then you could simply do: double (*grid)[N+2] = (double (*)[N+2]) mmap(NULL, ARRAY_SIZE, ... grid[4][5] = 2.0; // setting an element If N is not constant and your compiler doesn't support VLAs, then you need to...

Normalization in Java (dataset of doubles)

java,double,cluster-computing,normalization

The Encog Project wiki gives a utility class that does range normalization. The constructor takes the high and low values for input and normalized data. /** * Construct the normalization utility, allow the normalization range to be specified. * @param dataHigh The high value for the input data. * @param...

Can't seem to get .doubleValue() to work (I have the latest version of Java)

java,double

Your mistake comes from the class declaration. Formal parameter of generic may be T: public class queue<T> { Now you see that T has no method named doubleValue because you haven't constrained it. The following do what you want: import java.util.LinkedList; public class queue<T extends Number> { private final LinkedList<T>...

Issue with reading and storing data from .txt file into array

java,arrays,string,loops,double

The problem is you are not actually reading anything from the file. You do all the setup but you aren't reading. So when you have: File file = new File(name); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuffer stringBuffer = new StringBuffer(); String newString = stringBuffer.toString(); Here...

BoundField double show as many decimal places as needed

asp.net,gridview,double,dataformat,boundfield

Thanks for the advice @David W I ended up working it out anyhow. Although I couldn't find any documentation on it, you can give it proper custom formats. Therefore, the following solved my issue; <asp:BoundField DataField="theField" DataFormatString="{0:0.#####}" /> ...

how to create a result of double number with zero?

java,android,double

You passed the wrong pattern to DecimalFormat. Change "#.000" to "0.000" can solve your problem. The leading zeroes are not shown if you use "#". Here is the document of DecimalFormat, please refer to the part of Special Pattern Characters....

Convert DoubleBinding value to IntegerBinding

binding,javafx,double,javafx-8

You can use Bindings.format instead: sliderValue.textProperty().bind( Bindings.format("Sleep: %.0f", slider.valueProperty()) ); ...

Screen flickers when setting background

java,swing,double,buffer,flicker

My best guess is you have a race condition, where your while-loop is trying to update the BufferedImage, but Swing is also trying to paint it, meaning they are getting dirty updates between them. Also, you might be thrashing the Event Dispatching Thread, which could have it's own, long term...

“(int)Math.ceil(double)” always return 1 when values is greater than 0

java,casting,int,double,rounding

In all the outputs you printed (except the first one which is 0) Speed is smaller than 1 (7.026718463748694E-4, 5.27003884781152E-4, etc...). Notice the negative exponent. Therefore it's no wonder ceil returns 1....

Datagridview valuetype property not changing

vb.net,datagridview,double,value-type

Use the CellFormatting event to show your currency: Private Sub InventoryDataGridView_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles InventoryDataGridView.CellFormatting If (e.ColumnIndex = 2) Then e.Value = String.Format("{0:$0.00}", e.Value) e.FormattingApplied = True End If End Sub ...

Error when type float, no error when type double

java,floating-point,double

To specify that a number is a float is must end with an F or f so the code would read: float earthWeight = 195.0f; float moonWeight = earthWeight * .17f; ...

Understanding DBL_MAX

c,floating-point,double,double-precision

Double are represented as m*2^e where m is the mantissa and e is the exponent. Doubles have 11 bits for the exponent. Since the exponent can be negative there is an offset of 1023. That means that the real calculation is m*2^(e-1023). The largest 11 bit number is 2047. The...

Different results on CPU and GPU

c++,cuda,double,gpu,nvidia

Unless dev_s is thread local, you're going to have multiple threads writing to the same memory location here: dev_s[i] = dev_s[i-1] + 0.5*(dev_matrix[index]+dev_matrix[index-1]); ...

Shorten double value x digit

c,double,floor

The simplest solution to the decision tree problem you mention in comments would be to think in terms of the range of doubles that should go to a particular branch of the tree, rather than a single double. However, here is an attempt at the conversion function you asked for:...

Convert char array into double [closed]

c,printf,double,fgets,atof

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *txt1; char tam[13]; char tam1[13]; char tam2[13]; txt1 = fopen("99.c","r"); if(txt1 == NULL) { printf("No se puede leer el archivo"); return 0; } fgets(tam1,sizeof(tam1), txt1); double c = atof(tam1); printf("%f",c);// change from c } o/p: [email protected]:~/rabi/c$ ./a.out [email protected]:~/rabi/c$ vi...

Convert String Type to Double without Double.parseDouble()

java,string,nullpointerexception,type-conversion,double

Do it in this manner private double Doublify(String amountEntered) { try { if(amountEntered!=null){ Double double = Double.parseDouble(amountEntered); }else{ return 0.0; } } catch (NumberFormatException e) { return 0.0; } return double; } ...

Sorting an array of Strings with a numeric value, java

java,string,sorting,arraylist,double

You could have three approaches: Use Collections.sort with a custom comparator, which splits the string by : (and trims it) and then returns the .compareTo value of the numeric part of your string. Create a new object maybe call it CurrencyCorrelation which has 2 properties (currencyName and correlation maybe?). The...

double to int conversion not working using math.h functions in c

c,int,double,type-conversion,math.h

The trigonometric functions in math.h use radians, not degrees. You can convert the radians to degrees by multiplying by 180 / pi, ( 57.29577951308232). acos(0.13) would return 1.440427347091751 radians which multiplied by 57.29577951308232 gives the result of 82.53040768358306 degrees....

Java issue converting String to double

java,double

While I don't think that keeping trailing zeros is necessary, I think this is what you are asking for: DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); java.text.DecimalFormat df = new java.text.DecimalFormat(); df.setDecimalFormatSymbols(dfs); df.applyPattern( "###0.00" ); String s = "9.90" ; System.out.println("non formated d=" + Double.valueOf(s) + " formated d=" +df.format(Double.valueOf(s))); the...

Why does program provide -143155…when I only switched from int to double? [closed]

c,int,double

Change printf ("The number of miles per gallon is:%d",dailyDrivingCost(a,b,c)); ^ to printf ("The number of miles per gallon is:%f",dailyDrivingCost(a,b,c)); d conversion specifier is used to print an int, to print a double (or a float) you need the f conversion specifier....

MIPS float printing

double,mips

I'd just suggest printing the double in $f12, not just the float li $v0, 3 mov.d $f12, $f2 syscall ...

Reading FORTRAN-written double precision variables in R

r,fortran,double

Use sed or your favourite text editor to change the Ds to Es, I expect R will happily read the numbers after you do that.

Why one of the two values (they seem to be a Strings) is converted to Double, and the second one is not while parsing from JSON in Swift?

json,swift,parsing,double

Short answer: dictionary["gross_price_total"] is a string, and therefore as? Double fails. dictionary["gross_price"] is a number, therefore as? Double succeeds. However, println(dictionary) prints this number as "6.5678565676", so that it looks like a string. Long answer: Here is a complete example demonstrating the problem: let jsonString = "{ \"gross_price\" : 5.23,...

Get warning when convert double to NSDecimalNumber

ios,objective-c,methods,double,nsdecimalnumber

numberWithDouble: method of NSDecimalNumber returns NSNumber. In your method you want to return decimal so its OK if you allocate a new NSDecimalNumber with the decimal value (amount in your example). May use the following way to get rid of the error: -(NSDecimalNumber *)myMethod { double amount = 42; ......

Why is dividing double values returning null?

java,null,double,divide

Since you are using Double for your arithmetic, why not use the compareTo(Double anotherDouble)? Not sure if this is the source of your trouble, but it could be the == behaving in a way that you did not intend it to and returning false hence, the zero......

Are there limits of precision on the memory capacity of double?

java,double

Is my intuition that not all real numbers between the author's two limits would be appropriately held in memory as a double? Yes, you are right. Even the MOST obvious "doubles" cannot be stored correctly. For instance 0.1 is "1/10" - have you ever divided by ten in a...

How to parse “1,234.56” in Java as Double?

java,double,locale

1,234.56 is not French notation. (Something like 1.234,56 is). Change your locale to Locale.ENGLISH, Locale.US, or similar...

Difference between malloc() and simple declaration in fixed sizes [duplicate]

c,double,malloc,difference

double myArray[x]; Here memory is declared on stack Declared at compile-time, hence faster Accessible only in the scope of the declaring function,( globally if declared global) Will be freed if the declaring function returns generally used when the size of array is known at compile time myArray = malloc(x*sizeof(double)); Here...

precision of comparing double values with EPSILON in C

c,floating-point,double,epsilon

Bounds calculations are convoluted and have holes. See that upper_bound_x[n] == lower_bound_x[n+1]. Then when a compare occurs with (D->values[k][col2] == upper_bound_x[n], it will neither fit in in region n nor region n+1. // Existing code upper_bound_x[0]=min_x+interval_x; //upper bound of the first region in y lower_bound_x[0]=min_x; //lower bound of the first...

Calculating floating points as binary

double,bit-manipulation,point,floating

I agree with the comment that it should be done in binary, rather than by conversion to decimal and decimal multiplication. I used Exploring Binary to do the arithmetic. The first step is to find the actual binary significands. Neither input is subnormal, so they are 1.000101 and 1.00100001. Multiply...

C#, selecting certain parts from string

c#,string,select,double,stringreader

var point = "POINT (6.5976512883340064 53.011505757047068)"; var indexOfFirstBrace = point.IndexOf('(') + 1; var indexOfLastBrace = point.IndexOf(')'); var coordinates = point.Substring(indexOfFirstBrace, indexOfLastBrace - indexOfFirstBrace).Split(' '); var xCoordinate = coordinates[0]; var yCoordinate = coordinates[1]; ...

PHP preg_match double quote matching

php,regex,double,double-quotes

Your question is a bit confusing so let me describe what your regular expression does: preg_match('/[^a-zA-Z0-9 \"\'\?\-]/', $v) It will match any string which DOES NOT contain a-zA-Z0-9 \"\'\?\- Also you are escaping your " with \" which is not necessary. Try removing the back slash. The input test" should...

Check if two numbers exist in two dependent arrays - Java

java,arrays,double

Probably if I understood your data structure there is a problem in your for loop. If you store latitude and longitude in two arrays I imagine that a point in position n is defined by longitude[n] and latitude[n]. If this is how you store your points here is how you...

Using int, double and long in calculation of powers

java,int,double,long-integer

You could do it manual unless using Math.pow do something like this public static long powerN(int number, int power) { int result = number; while(power > 0) { result*=number; power--; } return (long)result; } ...

Converting decimal to fraction

java,split,double,decimal,fractions

You shouldn't work with doubles as you are losing precision and this can lead to serious errors. But in the case of 1.0001 the problem is that: Double.toString(1.0001) == "1.0E-4" Then you try to parse "0E-4" and you get 0 instead of 1. You could do the following if you...

defining decimal places of a double number in Java

java,double

Simply do this, double doubleValue=4.1; String.format(Locale.ROOT, "%.2f", doubleValue ); Output: 4.10 Using this approach you don't need to make use of DecimalFormat which will also reduce unnecessary imports...

How to display multiple leading zeros for floating point values in C++? [duplicate]

c++,stream,printf,double,stringstream

A couple of comments have mentioned std::setfill('0') and std::setw. While these are necessary, they're not sufficient to the task. For example, this code: std::cout << std::setfill('0') << std::setw(7) << std::showpos << 0.012; will produce: 0+0.012 as its output. This is obviously not quite what we wanted. We need to add...

Java method returns double | int

java,int,double,primitive

I'm not quire sure I understand the intention of returning a double or and int knowing that's not really possible for a single function to return different data types. What I think I understand from your sample code, is that if a String (For example, "123.0" doesn't matter how many...

Function to convert double to string with given options

c#,string,double,decimal

Try this: NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = decimalMark; nfi.NumberDecimalDigits = decimalDigits; return value.ToString("F" + decimalDigits.ToString(), nfi); ...

significant decimal digits of binary32 and binary64

floating-point,double,ieee-754,floating-point-conversion,significant-digits

First, for this question it is better to use the total significand sizes 24 and 53. The fact that the leading bit is not represented is just an aspect of the encoding. If you are interested only in a vague explanation, one decimal digits contains exactly log2(10) (about 3.32) bits...

Wrong output from an double operation

java,double,arithmetic-expressions

You must Typecast the ballsPlayed to double because ballsPlayed is an integer. It returns the integer part of (ballsPlayed % 6) / 10. Thus you got 0 except 0.4. Try this, double o = (double)(( ballsPlayed / 6 ) + ((double) ( ballsPlayed % 6) / 10 )); Here you...

JUnit's assertEquals denies assertTrue [duplicate]

java,junit,double,point

You're not overriding the Object#equals() method properly -- its signature should be as follows: public boolean equals(Object obj) { The parameter must be of type Object, you would then convert it to Point: @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return...

Create double by appending binary representations of two ints

c,binary,double,bit-manipulation,arc4random

When I print the binary representations of i and *(&i+1) and compare them to the binary representation of d, d is composed by appending *(&i+1) and i. So *(&i+1) comes first?! Why is this the case? the actual ordering of the bytes depends upon the 'Endian-ness' of the underlying...

Adding zeros in front of double

java,double

The easiest way is to create a DecimalFormat object, supplying the pattern yourself. The 0 characters indicate that a digit should be printed here, even if normally unnecessary. DecimalFormat df = new DecimalFormat("0000000000.00"); String formatted = df.format(-2.34); Outputting: -0000000002.34 With String.format, you can supply the total length as well as...

How do I convert a double into an n-character string using exponential notation?

java,string,formatting,double

If you're limiting you're exponential component to E0 to E99 (for positive exponential) and E0 to E-9 (for negative exponential), you could use a combination of DecimalFormat and Regex to format your results to be 6 characters in length. Something like: public static void main(String[] args) throws Exception { System.out.println(toSciNotation(1000123.456));...

Convert MATLAB type: from complex double to double

arrays,matlab,vector,double,complex-numbers

You can temporarily "remove" the minus sign, which causes the complex numbers: vec = [-2.5, 2, -1.5 , 1, -0.5, 0]; sign_vec = sign(vec); test = sign_vec.*((sign_vec.*vec).^1.4623); This results in: test = -3.8186 2.7555 -1.8092 1.0000 -0.3629 0 A generic way of your conversion involves the abs function: >> test...

String to double with decimal

string,matlab,double

str2double does what you expect. Type whos news or class(news) and you'll see the variable news is of type double: >> class(news) ans = double (You could use str2num to obtain the same result: news = str2num(s); also returns a double.) The fact that you see >> news = 128...

Add data fromEeditText to double

android,double

In your activity that accepts the input from the EditText: double value = Double.parseDouble(yourEditText.getText().toString()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (adding) { value = prefs.getFloat("your.float.key", 0f) + value; } else { value = prefs.getFloat("your.float.key", 0f) - value; } SharedPreferences.Editor editor = prefs.edit(); editor.putFloat("your.float.key", value); editor.apply(); In your activity that shows the...

Show price - double as Integer depending on its value in TextView - Android [duplicate]

android,textview,integer,double

double num; //eg 9.00 or 8.75 long beforeDecimal = (long)num; double afterDecimal = num - beforeDecimal; if(afterDecimal>0) display num; else display beforeDecimal; ...

Change decimal numbers in variable editor in MATLAB

matlab,double,decimal

Use format bank to get 2 decimal displayed. More details about the format function in the documentation. If you want to change how the variables are displayed in the variable editor, have a look at this page of the documentation. ...

Cast double to unsigned long C++

c++,casting,double,long-integer,unsigned

The problem arises with your variable distFromPlanets which resolves to -2.7e+9, as distEarthToSun = 9.3e+7 and newSunDist = 2.8e+9. Therefore 9.3e+7 - 2.8e+9 does approximately equal -2.8e+9. I'm no astronomer, but if you change your if statement to read if(selection <= 'a' || selection > 'h') the calculation for Neptune...

Given a microsecond value , how to accurately get a timeval struct? /*UPDATE GETTING NEGATIVE VALUE*/

c++,timestamp,double,rounding

Something like: timeval to_timeval(double usec) { return { usec / 1000000, usec % 1000000 }; } ...

Convert a string to a double for a if clause

android,string,if-statement,double

try this String text = "your string"; // example double value = Double.parseDouble(text); hope it helps ...

App Crashes With editText

java,android,if-statement,android-activity,double

in this line double cercuils = Double.parseDouble(s.toString()); you parse a String to a Double value. but maybe your String not be a number or it be empty. you can use try catch to if it is number parse it. double cercuils=0; try { cercuils = Double.parseDouble(s.toString()); } catch (NumberFormatException e)...

printing a double variable with %f and the terminal is displaying a “?” [duplicate]

c,printf,double

It sounds like you are linking against a version of printf that does not have floating point support. This is often the default configuration for compilers for embedded systems, because they don't have hardware FPUs and software floating point support uses precious space which most applications don't need. Consult the...

mysql convert float to double

mysql,double,alter-table

You can't. The FLOAT and DOUBLE types represent approximate numeric data values. They are stored in such a way that they can contain a wide range of numbers (from very big to very small), but at the cost of being a bit inaccurate. See Floating point types for more information....

Java: I want to get an Integer output in double datatype

java,double,decimal

You can use NumberFormat; the #-sign mean that decimals are only shown if they're non-zero. System.out.println("Value in " + new DecimalFormat("0.########").format(m)); ...

how can we have double digit range drop downs in rails forms? that gerates drop down with numbers like 00,01, 02 etc, instead 0,1 , 2 etc?

ruby-on-rails,double,range,digit

You could add something like this: "%02d" % number It will return for example "%02d" % 1 => "01" "%02d" % 51 => "51" For your example it could be: <%= f.select :credit, (0..500).map { |i| "%03d" % i } %> ...

VB.Net Double comparison after some additions

vb.net,comparison,double

If you take the example 3 you would see that the result is actually 3.0000000000000009. The problem is in the rounding of a double. If you change the data type decimal the problem is fixed: Sub Main() Dim i As Decimal = 2 For x As Integer = 1 To...

How to round a double to the nearest 10th place [duplicate]

java,double,number-rounding

In regards to your answer to yourself, you don't want to convert an object of type A to type B, operate on it, and then convert it back to type A. Not if you can do anything else. The following does what you want it to do: public double hypotenuse()...

Double not parsing correctly when high enough

c#,double,exponential

No it is not possible, as looking at the documentation double only stores 15 to 16 digits so it will revert to the short format if the number is larger than that. On the other hand ulong is 64 bits and contain a much larger number accurately, and if that...

Validator in composite throws ClassCastException when using java.lang.Double value

validation,jsf,double,classcastexception,composite-component

I can't reproduce your problem. It works for me with Mojarra 2.2.10 on Tomcat 8.0.21 even without explicit type attribute in <cc:attribute type="java.lang.Double">. As a workaround you could explicitly declare a converter as below in composite's input component: <p:inputText ... converter="javax.faces.Double"> But Mojarra 2.1.7 is really old (Feb 2012). You...

why “==” operator does not work [duplicate]

java,list,arraylist,double

You use .equals(otherObject) when comparing objects. You're comparing Double which is an object. If you were using double instead, a primitive, you could use == to compare values. Alternatively, get the double value from Double object: if (yourDoubleObject.doubleValue() == otherDoubleObject.doubleValue()) { // Do some things } ...

Will nullable value consider both null (“”) and DBNull at the same time

c#,asp.net,double,nullable,dbnull

Your method could simply be written as public double Difference(object val1, object val2) { double value1; double value2; double.TryParse(val1.ToString(), out value1); double.TryParse(val2.ToString(), out value2); return value1 - value2; } Assuming val1 and val2 are never null(same is true for your code too). Also I made the return type as double....

scanf issue when reading double

c,gcc,double,user-input,scanf

In your code, change scanf("%lf \n", &radius); to scanf("%lf", &radius); Otherwise, with a format string having whitespace, scanf() will behave as below (quoted from C11, chapter §7.21.6.2, paragraph 5) A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or...

float representing hours to hours:minutes:seconds using c#

c#,double,timespan

How about using TimeSpan.FromHours method? var ts = TimeSpan.FromHours(5.4898391027272906); Console.WriteLine(ts.Seconds); // 23 Don't use some integer calculations for time intervals. This is exactly what TimeSpan is for. By the way, you code won't even compile. Without any suffix, your 5.4898391027272906 will be double not float and there is no implicit...

Swift Downcasting AnyObject (Float) to String

ios,string,swift,double,downcasting

You can simply use variable interpolation in a string with Swift. First get your price and then just use it in a string with the $ prepended- var stockValueString="" if let price=dataArray[0]["stockPrice"] { stockValueString="$\(price)" } Also, note by (strong) convention variable should start with a lower-case letter. Class names start...

Java generate random double

java,random,double

What you can do is generate a random 64-bit value. This can give you Not-A-Number and +/-Infinity. Random rand = new Random(); double d = Double.longBitsToDouble(rand.nextLong()); Note: Random only produces 2^48 possible long values. You can use SecureRandom to generate all possible 64-bit values but this is much slower. In...

the usage of the long double

c,casting,double,long-integer

If you are using the version of Code::Blocks with mingw, see this answer: Conversion specifier of long double in C mingw ... printf does not support the 'long double' type. Some more supporting documentation for it. http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a If you went straight from float to long double, you may try just...

Trying to draw lines based on doubles but nothing shows?

java,swing,jpanel,double,graphics2d

x1 = 43.12929, x2 = 43.12976, y1 = -77.626956, y2 = -77.62679 These y values are outside the panel. AWT/Swing component visible coordinate space runs from (0, 0) to (width-1, height-1). Check where you are computing the values. If you want (0, 0) to be the center, you need to do some...

Multiplying variables and doubles in swift

swift,variables,double,multiplying

You can only multiple two of the same data type. var billBeforeTax = 100 // Interpreted as an Integer var taxPercentage = 0.12 // Interpreted as a Double var tax = billBeforeTax * taxPercentage // Integer * Double = error If you declare billBeforeTax like so.. var billBeforeTax = 100.0...

Find out if you're reading int or double using fscanf

c,parsing,int,double,fscanf

Since float can hold an integer but not vice versa. Just read the data like a float and check if it is an integer using something like if(ceilf(f) == f) { i=(int)f; } //Here i is an integer and f is the float you read using %f To see more...

Validate double number in current culture

c#,parsing,double,cultureinfo,currentculture

On my machine the following throws a FormatException, as expected: var number ="10,10"; double value = double.Parse(number, NumberStyles.Float, CultureInfo.InvariantCulture); I suspect you're using NumberStyles.AllowThousands. For example, the following will return 1010: var number ="10,10"; double value = double.Parse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture); UPDATE in response to comment: ... but if...

Large number of operations on double data type producing zero as result

java,floating-point,double

The output is zero because double has a limited percision, and if you multiply a number lower than 1 by itself enough times, you'll get a result too small to be distinguished from 0. If you print d after each iteration, you'll see that it becomes 0 quite fast :...

Type mismatch: cannot convert from boolean to double

java,double

You are comparing a boolean value to a double. Here is a breakdown of what that line is doing: price == minprice will give a boolean indicating if price is equal to minprice, which you are then asking if it is less than .20*minprice. So you are asking if the...

C++ - How to correctly cast double to int

c++,casting,int,double,precision

Almost all widely available hardware uses IETF754 floating point numbers, although C++ does not require it. Assuming IETF754 floating point numbers and a direct mapping of ::std::sqrt to the IETF754 floating point square root operation, you are assured of the following: 16 and 4 can both be represented exactly in...

Double.ToString returns empty for 0

c#,double

From The "#" Custom Specifier Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. It will display zero only if it is a significant digit in the number that is being displayed. If you wanna...

Can std::uniform_real_distribution(0,1) return a value greater than 0.99999999999999994?

c++,c++11,random,double,double-precision

The maximum value dist(engine) in your code can return is std::nextafter(1, 0). Assuming IEEE-754 binary64 format for double, this number is 0.99999999999999988897769753748434595763683319091796875 If your compiler rounds floating point literals to the nearest representable value, then this is also the value you actually get when you write 0.99999999999999994 in code (the...

Why GraphicsContext uses methods with double params?

java,swing,javafx,int,double

drawRect in inherited from Graphics which uses int to specify the co-ords & size. The Graphics2D object on the other hand, is capable of dealing with graphics values that lie 'between whole pixels'. To compensate it will typically render a dithered pixel (part way between the drawing and BG color)...

C# losing precision thus making equation result 0

c#,double,precision

You could work with logarithms, and handle the result later as you need. foreach (var word in fileDictionary) { dictionaryTotal.TryGetValue(word.Key, out percent); temp = percent; A += Math.Log10(temp); B += Math.Log10(1 - temp); } You could then operate the resulting logarithms, instead of the resulting numbers....