Odd Floating Point behavior

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Post Reply
User avatar
Posts: 16
Joined: Thu Apr 06, 2017 9:57 am
Projects: Bondage Island, Lucretia's Legacy

Odd Floating Point behavior

#1 Post by Amaraine » Sat Dec 16, 2017 8:53 am

I was porting a game over from straight Python, and noticed a strange phenomenon. I figured out a way around it, but I was wondering why it happened.

In Python 3.6...

object.variablea += max ((object.variableb - 7) / 5, (object.variableb - 10) /2)

variablea is a float equal to 0.0
variableb is an int equal to 11

so, (11-7) / 5 = .8, and (11-10) / 2 = .5, so the whole expression evaluates to .8 and variablea ends up being .8 at the end.

In Ren'py (current version), inside a python block and a function, however, variablea ends up being 0.0. And evaluation in the console shows that

(11-7) /5 = 0 (integer 0) -- that is, for the version of Python in Ren'py it returns an integer rather than a float. Why is this?

(The fix I found is to change 5 to 5.0, and 2 to 2.0, which makes both expressions return floats as intended. But that wasn't necessary when I was running the whole thing through Python directly.)
Author of Bondage Island and Lucretia's Legacy

User avatar
Miko-Class Veteran
Posts: 925
Joined: Tue May 30, 2017 6:10 am
Completed: None... yet (as I cannot draw very well)
Projects: An un-named 3d anime based trainer game

Re: Odd Floating Point behavior

#2 Post by Remix » Sat Dec 16, 2017 9:07 am

Ren'py runs on Python 2.7 which is/was a right pain for doing basic math with.

General advice is to do as you likely are and convert each value to a float before doing the sum...
value = float(a) / float(b)

Python 3 made it a lot more sensible

Post Reply

Who is online

Users browsing this forum: No registered users