numbers,computer-science,representation , Gaps between successive floating point numbers

Gaps between successive floating point numbers


Tag: numbers,computer-science,representation

(all numbers discussed are in decimal)

lets say we have a floating point data type that is like :

m * 10 ^ e

where m is the mantissa . and max mantissa size is 1 ( 0 <= m <= 9);

e is the exponent and its size is  -1 <= e <= 1

we say our data type Max value is 90 and its Min value is 0

BUT : that does not mean we can represent all numbers that are in this limit . we can only represent 27 numbers ( 9 * 3 ) excluding zero.

specifically we can't represent 89 in this way since it has a two digit mantissa (and non of them are zero).

so technically analogous to the above descriptions . in a float data type (in any programming language) there must be some integers between Max and Min values that we cannot store in a float data type .

is the above argument sound . if it is please give an example how to show this in java or c ?


Your reasoning is perfectly sound. The easiest to show it is be example, as you did.

An non-representable example

Consider the "usual single floating point" format, as defined by IEEE-754, it has 7 exponent bits, thus a range beyond [-2^127,2^127].

It also has 24 mantissa bits, so let's consider 67108864, 67108865 and 67108866. Those numbers are respectively 2^26, 2^26+1 and 2^26+2.

Try to normalize them to write them in the floating point format, and you'll see that

Thus you have an example, like 89 : 67108865 is not representable in a float.

* except for subnormals, see below (expanding on the comment)


Indeed I skipped a part here. The exponent is not directly encoded in the bits that are reserved to it, it is biased. In the case of single floating points, the bias is 127.

So our 26 is actually represented by 26+127, thus 153. Stealing the following image from wikipedia :

negative zero drawing to illustrate floating point format

If you take those numbers (sign, exponent and mantissa) as they are written and want to express a non-subnormal number, you get : (-1)sign * 2(exponent-127) * 1.mantissa


Once we reach the smallest possible exponent, that is once we write it 0 and mean -127, we stop supposing the initial 1. This, way, we can represent numbers smaller than 2-127 (by sacrificing precision, because we will have leading 0's on the mantissa).

We then have : (-1)sign * 2-127 * 0.mantissa

In particular, when the mantissa is all 0's, we have 0, and this is intended : now a number that has only 0's in its binary representation is read as 0. In some way, 0 is the smallest of subnormal numbers (though in practice people consider it just a special case on its own).

Other special cases are when the exponent is all 1's. If the mantissa is all 0's then you have +/- infinity (depending on the sign), and if some mantissa bits are set you have a NaN.


Comma Automatically Being Added to TextField in Swift

I'm working on a status bar application. Currently all I have is a drop down menu that either quits the app or opens a preferences window. There is a textfield in the window that will be for a number value. While testing I noticed that when I used .orderOut to...

Android Edit Text - Input Type Number not setting max value

So what I would like is a very simple edit text with input type number or decimal that has the following aspects. Number Edit Text: You can only type up to Long.MAX_VALUE / Long.MIN_VALUE, so I can cast to a long without modifying the user's input. Number Decimal Edit Text:...

Sort array with objects on property of objects

I would like to sort an array of objects by a property of the specific object. This is my array with objects: As you can see I have an array $all_studies with 2 objects. How can I now sort on the graduationYear property of the objects? So I would like...

json_decode AND json_encode long integers without loosing data

As noted in the PHP documentation, when json_decodeing a data structure containing long integers, they'll be converted to floats. The workaround is to use JSON_BIGINT_AS_STRING, which preserves them as strings instead. When json_encodeing such values, JSON_NUMERIC_CHECK will encode those numbers back into large integers: $json = '{"foo":283675428357628352}'; $obj = json_decode($json,...

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

I don't seem to understand how Integer.MAX_VALUE and Integer.MIN_VALUE help in finding the min and max value in an array. I understand how this method (pseudocode below) works when finding the min and max values: max = A[0], min = A[0] for each i in A if A[i] > max...

Bash Case statement: check whether string ends in number

I'm writing a script and I'm kinda stuck at the following part: Inside a case statement, I want to check whether or not the "--sn" command is followed by a number (1-254). I thought i'd just use --sn*, but apperently * doesn't work for numbers? case "$1" in --sn* )...

List files that only have number in names

I have a directory with these files: 1.html 22.html 333.html zxc.html I want to get a list of the html files that only have digits in their name: 1.html 22.html 333.html I thought this would work find . -regex '^[0-9]+\.html' or ls -al | grep -E '^[0-9]+\.html$' But I get...

Need workaround to treat float values as tuples when updating “list” of float values

I am finding errors with the last line of the for loop where I am trying to update the curve value to a list containing the curve value iterations. I get errors like "can only concatenate tuple (not "float) to tuple" and "tuple object has no attribute 'append'". Does anyone...

PHP subtract a percentage result

$temp_price_1 = round($price * ((100-$sale_percentage) / 100), 2); $price = $temp_price_1; im using this code to subtract a percentage from a number, for this example my starting number for $price is 24.99 and the $sale_percentage is 50.0 this result is the $temp_price_1 being 12.5 which is correct, however i need...

PHP Allow only numbers with 2 decimals

I need a function to check if number have 2 decimals or not. For example: $number = '1.00'; // Valid $number2 = '1'; // Not valid $number3 = '1.000' //Not valid ...

how to return a number with 2 decimal places all the time from a function

I have a random number generator function that returns a random number. It looks like the problem is that sometimes it returns only one decimal place the, tenths place(i think it's called). I always want it to output a number with 2 decimal places (some times i would get 10.5...

Function to determine largest prime factor

I am trying to write a function in JS that returns a number's maximum "prime" factor. For example, if I ran maxPrimeFactor(57), I should return a 19. However, my function only works part of the time. I have written a helper function called isPrime that returns a boolean that indicates...

What's the best way in JavaScript to test if a given parameter is a square number?

I created a function that will test to see if a given parameter is a square number. Read about square numbers here: If the number is a square number, it returns true and otherwise false. Negative numbers also return false. Examples: isSquare(-12) // => false isSquare( 5) // =>...

Would this function be O(n^2log_2(n))?

So I am given a function like 65536 n2 + 128 n log2n and the only way that this would be O(n2 log2n) is if C = 65664, n0 = 2 for all n ≥ 2 since C1 = 65536 n1 = 2 when 65536 ≤ C1*n2 and C2 =...

Why isn't Pythons randint Function actually Random?

I've been coding in python for awhile, and I happened to stumble upon Codecademys exercises and one of the projects was to create a battleship game that randomely places a 2x1 battle ship in a 5x5 grid. I noticed a pattern after my girlfriend correctly guess where the ship was...

Convert strings to numbers without losing decimals

I'm developing a map and I have to save this parameters on Parse database: lat.: 20.6350 . Long: -103.5334 The problem is when i convert them into numbers, that function converts 20.6350 to 20.635. ¿What can I do in order tu preserve the last zero?...

PLSQL invalid number error after fetch

sorry if this is an confusing post and the style is not proper but this is my first question but im having an error after i want to fetch c_latlong : the things he will fetch are: LAT value : 50,9459744669855 LON value : 5,9704909091251 ORA-01722: invalid number ORA-06512: at...

Exception (integer overflow) when initializing 64-bit Mersenne Twister,visual-studio-2010,random,numbers,64bit
I am using the 64-bit verison of the Mersenne Twister, specifically the version: A C-program for MT19937-64 (2004/9/29 version). Coded by Takuji Nishimura and Makoto Matsumoto. and am receiving an integer overflow when compiling into the Release but don't get the exception during run-time in Debug. I have integer overflow...

Java: 2d array - making it “torus” like

I am facing following problem: I have a board of size MxN squares. What is the best way to make it in java so that when there are coordinates given which are out of bounds (or with negative values), it will return square from the other side of the board?...

No line number shown for run-time error from Python module

Most Python errors produce traceback showing the line number of the offending statement. But for some reason some run-time errors do not. For instance, running "python -m" on a module containing just the two lines: args = {} if len(args > 2): print("this is a run-time error. Should be:...

Transition between decimal or double numbers

Imagine a number 10, then after user clicks a button it changes to 100. But how to make an efficient transition 10 -> 100, that will display values like 12, 15, 18, ..., 97, 100 over 1 second. I've seen something like that in "Cookie clicker" but couldn't find anything...

How to round a number up and add numeric punctuation

I've got the following pen: I cant quite figure out how to round the number up so you don't break the punctuation. I need to round the number up as I don't want to see a value like 33,333.,333 //ADDS PUNCTUATION EVERY THREE CHARACTERS $('input.numericpunctuation').keyup(function(event){ var oNum= $(this).val(); //...

Solving a complex recurrence relation for the Traveling Salesman

I need to solve the exact time complexity for the brute force version of the Traveling Salesman using a recurrence relation. I've worked out the recurrence relation to be as follows: T(n)=T(n-1)*(n-1)+1 But I'm having trouble reducing that that to a closed form of the function, and thus get the...

How do I square a number's digits?

How do I square a number's digits? e.g.: square(21){}; should result in 41 instead of 441...

Computer architecture - How to find the addresses in a block

A cache memory with 4 KiB, each block is 16 words, there are 64 lines in the cache. Tag = 18 Index = 6 Block offset = 4 Byte Offset = 2 I want to know for block number 448 what is the first address in the block and what...

How to allow more entry and return factors for Prime Checker [Java]?

I set out to write a Prime Number Checker: import java.util.Scanner; public class PrimeChecker { int userEntry; int even_check; int odd_check; final void run(String[] args) { Scanner jaiho = new Scanner(; System.out.printf("Please enter a prime number: %n"); userEntry = jaiho.nextInt(); even_check = userEntry % 2; // This is to get...

First common element from different lists of numbers

I am trying to find the first common number (FCN) from e.g. 5 individual number lists. For example the 5 number lists are these ones: list_1 = [13579875, 25732, 3541, 56732, 1567, 20546, 10, 68971] list_2 = [1856721, 25724, 3541, 56732, 1567, 20546, 10, 68971] list_3 = [2354074, 25732, 3541,...

Remove leading zeros from input type=number

I noticed that if i use the leading zeros are not removed. I also saw a lot of discussion on how keeping leading zeros. For example "000023" and "23" are the same number and i think that it doesn't make sense keeping those zeros....

Counting up “broadly”: Not 0,1,2,..,9,10,11,..,99 but 00, 01, 10, 11, 02, 12, 20, 21, 22, 03, .., 99

When a counter is made up from a fixed number of digits (2 in the title), standard counting-up works by incrementing from the least to the most significant digit and upon overflow reset it. I want to count differently: A 4 digit number in base-10 would be counted up in...

Convert a large int to a float between 0.0f and 1.0f

I'm working on a project where I have a pane that goes from 0 to 500 on the x and z, but I need to convert that coordinate (from 0 to 500) to a float in the range of 0.0 to 1.0 in because it is required from some of...

Calculate the average for an arbitrary number of arguments

I'm trying to calculate a function that will return the average for an number of integer arguments. Who can help? var Calculator = { average: function(x) { var num = 0; for (var i = 1; i <= x.length; i++) num = num + x[i]; var divide = num/x.length; return...

Unable to increase extremely large number by one in JavaScript

I'm trying to increase by one this number: 9223372036854775808: var number = 9223372036854775808; var plusOne = number + 1; This should yield 9223372036854775809, but it instead yields 9223372036854776000. Why? More important, how can I fix this?...

af:convertNumber element removes zero in the end of the value

My code: <af:inputText id="it1" label="Test"> <af:convertNumber groupingUsed="true" type="number" messageDetailConvertNumber="#,###,##" maxFractionDigits="2"/> </af:inputText> When I type 100,51 -- everything is fine, but if I would type 100,50, then '0' will be removed and entered value will be 100,5. How can I leave this '0' in the end? I need <af:convertNumber> element for...

Autoboxing 0 to Generic Number

Maybe I just have a knot in my synapses... public static <T extends Number> T firstNonZero(T... values) { for (T value : values) { if (value.doubleValue() != 0.0) { return value; } } return (T) 0; // Cannot cast from int to T } I guess I don't need to...

Getting NaN Instead of Number

I am having a small problem with the code below, instead of a number I am getting NaN. What's wrong? for (var i = 0; i<100; i++) { x = i ^ i result = x + result; } var y = result - (result ^ result); console.log(y); ...

Check if given number is Even, Odd or Neither in PHP? [duplicate]

This question already has an answer here: php test if number is odd or even 11 answers How can I get if a number is even or odd or neither (have decimal, like 1.5) with PHP? I know that there are operators like *, /, but they did not...

How can I 'change in number' or 'change in digits' in Vim

I'm regularly editing CSS in Vim and need to change a value like: width: 300px; to something else like: width: 178px; Normally what I do is navigate to the 3 in 300 and type cw to change the word. But if I do this I have to type the px...

How to Make this Code Work (isdigit) [duplicate]

This question already has an answer here: Check if input is float else stop 6 answers So, I'm creating a program that calculates the area of a triangle, and I need it to tell the user if he typed a letter or a negative number, in order, I created...

How to parse table of numbers in C++

I need to parse a table of numbers formatted as ascii text. There are 36 space delimited signed integers per line of text and about 3000 lines in the file. The input file is generated by me in Matlab so I could modify the format. On the other hand, I...

Regex: get every number that doesn't has an other number before or after itself

The thing that I have to do is to extract every 'single' number, that doesn't has another number right before or after itself. Then I have to replace this number with an number, that is incremented with 1. I now want to a Regex that gets every single number from...

MATLAB - Extracting numbers from a cell array of strings

I want to extract a number from a text file. First I read the file and import is as a cell array of the form: A = { '1 0 0 0 - 0: 0.000741764' '2 0 0 0 - 0: 100' '3 0 0 0 - 0: 100' '4...

R: replace the whole part of a number but keep the decimal part unchanged

ok I'm very new to R and this is a general question. I have various numbers and I want to replace the whole part and keep the decimal part unchanged. For example I have values from 25.01 to 25.99, I want to replace 25 with 10 but keep the decimal...

python dictionries when keys are numbers [duplicate]

This question already has an answer here: Why is the order in Python dictionaries and sets arbitrary? 5 answers I have a question about dictionary properties in python when the keys are number. in my case when I print a dictionary with number keys the result of print will...

How to make a range in Numbers (iWork) using JXA

I'm using JXA for automating a process using Numbers app. What I need is to select a range of cells to apply width, but JXA doesn't allow me to get them. According to apple documentation I only need to use make or push the created object inside of array, but...

Extract numbers from a string in java

I want to extract numbers from a string like: str="good_mor9ni13ng_23guys "; The output should be an array [9,13,23]. How should I proceed?...

Return highest and lowest number in a string of numbers with spaces

Let's say I have a string of numbers separated by spaces and I want to return the highest and lowest number. How could that best be done in JS using a function? Example: highestAndLowest("1 2 3 4 5"); // return "5 1" I would like the both numbers to be...

How i can get the numbers on the left and the right of the given element?

Given a string: $pages = "1,2,3,4,5,6"; Create a function that gets the numbers on the left and the right of the given element. I expect this ouputs: pagination(1); // array('prev' => null, 'next' => 2); pagination(2); // array('prev' => 1, 'next' => 3); pagination(6); // array('prev' => 5, 'next' =>...

How do you use a range of numbers in an if statement in livecode?

How do you do a range of numbers in livecode? I tried using "-" like this if the loc of the image "yellowdisck.png" is 0 50,0-640 then But this doesn't work....

Reduce number to single digit using recurssion

$result = reduce($number); function reduce($number) { $new_number = 0; if($number < 10) { return $number; } $q = floor($number / 10 ); $r = $number % 10; $new_number = $q + $r; if($new_number <= 9) { return $new_number; } else { reduce($new_number); } } I want to sum the numbers...

Weird output, when number starts with 0

1. script: $num = "00445790"; echo $num; returns: 00445790 2. script $num = 00445790; echo $num; returns: 2351 Can somebody explain why I get 2351 on the second script?...