Python multiplication equivalent to integer division
Asked Answered
G

2

12

In python using // for division forces the result to be an integer. Is there an equivalent for multiplication?

For example, assume I have an integer W which I scale by a float f. It could be nice to have an operator such as .*, so that:

int(W*f)==W.*f

Would be True.

Goldiegoldilocks answered 27/1, 2020 at 8:22 Comment(1)
T
6

// does not "force the result to be an integer", this may be coincidentally true, but describing the operator in this presumptuous way is (I believe) resulting in you thinking that there should be other analogous features, which there really aren't. // is "floor division", which any type can overload to have any desired behaviour. There is no "floor multiplication" operator. If you want the result of multiplication to be forced to an integer, you've already shown a perfectly acceptable and straightforward way to do this:

int(W*f)
Tollhouse answered 27/1, 2020 at 8:34 Comment(2)
OP wants infix notation, not a function.Tallu
@Tallu OP's explicit ask was "In python using // for division forces the result to be an integer. Is there an equivalent for multiplication?". I have tried to respond to this directly, while addressing perceived misconceptionsTollhouse
A
5

No, and there is unlikely to be one added, for two reasons.

  • The current options are short and built-in
  • There is no ambiguity to be resolved

When you take 12/5 you can reasonably want a integer, quotient, or real, all of which are well defined, take different values in python (without infinite floating precision) and behave differently.

When you multiply 12*5, you could also want those three, but the value will be identical.

For something like pi * 100000, you would need to know the type to end up with as well as the resolution technique for e.g. float to integer (floor, ceiling, round closest, round .5 up, round .5 down, bankers rounding). Without strong types this becomes a mess to hand down from above, and easier to delegate to the user and their own needs or preferences.

Annabal answered 27/1, 2020 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.