473,898 Members | 3,815 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Working with decimal points

How come:

sum = 1/4
print sum

returns 0? 1/4=0.25, not 0. How do I fix this?

-- /usr/bin/byte

Apr 8 '06 #1
8 1967
Byte wrote:
How come:

sum = 1/4
print sum

returns 0? 1/4=0.25, not 0. How do I fix this?


Make sure there is at least one float in your equation. In your example
Python is doing interger math for you and returing the floor. You need
to give it a hint that you would like to do floating point math.
sum = 1.0/4
print sum 0.25 sum = 1/4.0
print sum 0.25


Apr 8 '06 #2
That dosnt work either:

sum = 0.1+1/4
print sum

Just returns 0.1

Apr 8 '06 #3
"Byte" wrote:
How come:

sum = 1/4
print sum

returns 0?
because 1 and 4 are integer objects, so 1/4 is an integer division, which
rounds down to the nearest integer.
1/4=0.25, not 0. How do I fix this?


use floating point numbers:

1.0/4.0 = 0.25

or convert one of the numbers to a float:

float(1)/4 = 0.25

</F>

Apr 8 '06 #4
Fredrik Lundh's way works: thank a million!

Apr 8 '06 #5
Byte wrote:
That dosnt work either:

sum = 0.1+1/4
print sum

Just returns 0.1


That's because the 1/4 is executed first, and the problem mentioned
still applies (i.e. you get a 0, then add it to 0.1).

The best fix for you might be simply to place this line at the start
(before all other code) of your module:

from __future__ import division

That will change the way simple division works to give you the results
you expected. See the online docs for more background on this.

-Peter

Apr 8 '06 #6
On Sat, 08 Apr 2006 08:21:06 -0700, Byte wrote:
How come:

sum = 1/4
print sum

returns 0? 1/4=0.25, not 0. How do I fix this?


By default, / does integer division, not floating point. In integer
division, 1/4 is 0, exactly as calculated.

(How many fours go into one? Zero fours go into one, with one remainder.)

There are two ways to change this:

(1) Convert at least one of the numbers to a float first:
1.0/4 0.25 1/float(4) 0.25

but be careful, this one doesn't do what you want:
float(1/4) 0.0
(2) Run the following command at the start of your program or in your
interactive session:
from __future__ import division
Now division will behave as you expect:
1/4 0.25

and you can use // for integer division.

Now that you can do floating point division, I peer into my crystal
ball and predict your next question: why is Python so inaccurate?
1/10

0.1000000000000 0001

Answer: it isn't. You've discovered a mathematical limitation that 1/10
cannot be written exactly in any fixed number of binary places, just like
1/3 cannot be written exactly in any fixed number of decimal places.

See also:

http://www.python.org/doc/faq/genera...-so-inaccurate

http://docs.python.org/tut/node16.html
Hope this helps.
--
Steven.

Apr 8 '06 #7

Byte wrote:
That dosnt work either:

sum = 0.1+1/4
print sum

Just returns 0.1


You get precedence right? Your equation does not evaluate from left to
right. 1/4 happens first, and since there are no floats you get 0.

in that equation you basically are doing this:

sum = 1/4
print sum
0

sum = 0.1 + sum
print sum
0.1

Apr 8 '06 #8
"Byte" wrote:
That dosnt work either:

sum = 0.1+1/4
print sum

Just returns 0.1


division has higher precedence than addition, so 1/4 is calculated first,
and the result is then added to 0.1.

and as I've already explained, 1/4 is an integer division, so the result
is rounded down to the the nearest integer (0). in other words, your
expression boils down to

0.1 + 0

which is 0.1 [1].

the precedence order is explained here:

http://docs.python.org/ref/summary.html

</F>

1) or at least a close approximation of it; see
http://docs.python.org/tut/node16.html

Apr 8 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
9018
by: Enno Middelberg | last post by:
Hi, I'm sure someone asked this question before, but I can't find the solution on the web or in the groups. I want to print out columns of numbers which are aligned at the decimal point, eg: 123.45
15
12842
by: Kay Schluehr | last post by:
I wonder why this expression works: >>> decimal.Decimal("5.5")**1024 Decimal("1.353299876254915295189966576E+758") but this one causes an error 5.5**1024 Traceback (most recent call last):
2
7172
by: intrepid_dw | last post by:
All I am writing a C# WinForms application which is giving me some problems. The application consists of a form containing an empty Tab control to which TabPages are added dynamically (at runtime). Each TabPage contains a single Panel control. My intent is to draw a graph on that Panel control dynamically, with the code capturing a point at each update interval, then calling the Graphics.DrawLine method of the panel
0
2514
by: Sam | last post by:
I am trying to use a Simple form with 3 fields from SQL NorthWind Database (Order Details Table with 3 Fields. - OrderId, ProductId and Unit Price). The Field Unit Price has a data type of 'Money Type'. All I want is to able to edit/view/insert 'UnitPrice' field with 2 decimal points instead of 4 decimal points. If I use: Bind("UnitPrice", "{0:c}") in Edit Template, I got: "Input string was not in a correct format...". Although this...
1
1781
by: ianhen | last post by:
Hi I have a Web Form which I need to get results shown to 2 decimal points only. In the Head I have: - function heatoutput() { var vWidth=document.heatcalculator.roomwidth.value; var vLength=document.heatcalculator.roomlength.value; var vHeight=document.heatcalculator.roomheight.value;
0
1341
by: apple27 | last post by:
Hi, Appreciate your guys help.. Im a newbie in OWC.Trying to search for OWC objects to complete a few charts. Still having difficulty on this :- My questions: 1. I need to come out with a chart - 2 data fields. ChartSpace3.SetData e.chDimValues, e.chDataBound, "Goal" ChartSpace3.SetData e.chDimValues, e.chDataBound, "Percentage"
3
15991
neo008
by: neo008 | last post by:
Hi all, I am using some variables as "Double" and some text boxes set "DataFormat" property to "Number with two decimal points" for currency calculations. I perform some typical mathematical operations on them and in some cases I see result having more than two decimal points. How can I restrict or round-of to only two decimal places. I'm using VB6.
3
3860
by: Mike Howarth | last post by:
Hi Seem to be having a bit of brainfreeze this evening. Basically I'm reducing an array of prices like so: This gives me a string of '86.00.00' which I am trying to use with decimal objects. Python 2.4 is not particularly happy with this. Additionally I can't simply convert the string to a decimal as it would be
6
16934
Mohan Krishna
by: Mohan Krishna | last post by:
Hi everyone! I am entering only numbers with decimal points/values in a TEXTBOX on the VB form. I need to get only the decimal values. How can I? Please help me as I tried in this way (for 2 Decimal places) VB6 Dim x As Double Dim dc As Integer, dcStr As String
0
9994
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9842
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11265
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10859
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9662
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5882
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4712
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4298
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3309
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.