views:

73

answers:

3

In IronPython is there any way to force the expression containing integer values to be calculated as floating point. For instance, I'd like the expression

1/3

to be evaluated as

1./3. 

with the result 0.333...

I need this to make a simple run-time expression calculator within a C# project by means of IronPython. I cannot force users to input expression with trailing decimal points.

+2  A: 

If your users are entering values anyway, then presumably you are converting the values to ints. So simply convert them to float instead.

val1 = float(raw_input())
val2 = float(raw_input())
print val1/val2
Daniel Roseman
+4  A: 
from __future__ import division

print 1 / 3
print 1 // 3
Ignacio Vazquez-Abrams
Beat me to it by about a second. +1
None
I'm resisting the downvote since you're correct, but the fact that the Python guys decided to change the semantics of a basic arithmetic operator after so many people had written so much code already - it still seems insane to me. I don't know how well IronPython tracks the Python version, but this nasty surprise is going to happen to a lot of people as they move from Python 2 to Python 3. A lot of calculations with precisely defined rounding behaviour will no doubt silently break, so trusted apps will give wrong results.
Steve314
@Steve314: And? Python 3 is hardly new. If third-party documentation isn't up-to-date then there's nothing the Python devs can do about that.
Ignacio Vazquez-Abrams
@Ignacio - what about all the apps written for Python 2, or for that matter Python 1, which haven't been touched for years? We live in a world where Cobol and Fortran code written in the seventies is still in use. If it ain't broke, it is well known that you shouldn't fix it. That's what I mean by "trusted apps". But then, someone installs a new Python version, and suddenly the basic arithmetic operators don't do what they did yesterday, and that crucial financial calculation for an important contract, or that load calculation for a bridge, silently gives a wrong result.
Steve314
The point is that the Python devs *chose* to change the semantics of a basic arithmetic operator. It was always blatantly obvious that this was going to cause problems. The Python devs simply set up their excuses for why they can't be held responsible - "there's lots of warning for anyone who spends their life checking for possible semantic changes in their languages", "if you use the special Python 2.6 option it'll probably tell you about the problem" etc.
Steve314
+1  A: 

You may force a floating point division like any of these, no matter if anything is imported from __future__:

print val1 / (val2 + 0.0)
print (val1 + 0.0) / val2
print float(val1) / val2
print val1 / float(val2)
pts
Great! This is exactly what I needed. Unfortunately I cannot mark all the correct answers as accepted. So I'll +1 to everybody and accept this one.
Max