Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a whole number float divided by itself guaranteed to be 1.f?

If I write:

int x = /* any non-zero integer value */;
float y = x;
float z = y / y;

Is z guaranteed to be exactly 1.f ?

like image 765
j b Avatar asked Jun 30 '17 12:06

j b


People also ask

Can you divide a float?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.

What happens if you divide float by INT?

If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point.

Does division in Python return a float?

According to Python 3 documentation, Python when divided by integer, will generate float despite expected to be integer.

When a number is divided by itself the cutest is?

All Answers (9) Hope it will help! Carla, you have the answer in your question: 'any number divided by itself is equal to one' a zero is a number too, so 0/0 equals 1. Cheers!


Video Answer


2 Answers

If your C++ implementation uses IEEE754 then yes, this is guaranteed. (The division operator is required to return the best possible floating point value).

The only exceptions for y / y, in general, not being 1.f are the cases when y is NaN, +Inf, -Inf, 0.f, and -0.f, or if you are on a platform where int is so wide that certain instances of it cannot be represented in a float without that float being set to +Inf or -Inf1. Setting aside that final point, in your case that means that int x = 0; will produce the only exception.

IEEE754 is extremely common. But to check for sure, test the value of

std::numeric_limits<float>::is_iec559;

1A platform, for example, with a 128 bit int and an IEEE754 32 bit float would exhibit this behaviour for certain values of x.

like image 144
Bathsheba Avatar answered Oct 21 '22 06:10

Bathsheba


No, not in all cases, even for IEEE754.

For example, with int x = 0;, you'll get NaN. (Live)

like image 33
Baum mit Augen Avatar answered Oct 21 '22 05:10

Baum mit Augen