The fractions are incomplete [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm working with the fractions module of python.
I'm trying to get fractions that aproximates 2*.5. The problem is that when I use the Fraction command, it doesn't returns me what I want, because, for example, in i=2, the fractions that returns is 146666667/1000000000, but i want that it returns me 17/12 (The third aproximation of 2*.5). How i can solve it?
The code is this:
ai=2
bi=1
n=5
for i in range(n):
ai=2+float(bi)/ai
F=fr.Fraction(str(ai-1))
print F
Can someone help me, please?

If you are going to work with fractions, don't do part of the calculation with floats. You can perform all the arithmetic with respect to fractions by making ai a Fraction:
import fractions
ai = fractions.Fraction(2)
bi = 1
n = 5
for i in range(n):
ai = 2 + bi / ai
F = ai - 1
print(F)
yields
3/2
7/5
17/12
41/29
99/70

Searching a little bit I found this function limit_denominator(...), that could help you:
F = fr.Fraction(str(ai - 1)).limit_denominator(100)
Output:
3/2
7/5
17/12
41/29
99/70
Read more in Fraction docs.

The fractions module is a great utility. Thanks for bringing it up here.
To control the denominator to more reasonable values, try adding limit_denominator() like this:
from fractions import Fraction
ai=2
bi=1
n=5
for i in range(n):
ai=2+float(bi)/ai
F=Fraction(str(ai-1)).limit_denominator(1000)
print i, F
Output now looks like this:
%run "testFractions.py"
0 3/2
1 7/5
2 17/12
3 41/29
4 99/70

Related

perform arithmetic operations python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
given the number 12345 = 1x10^4 + 2x10^3 + 3x10^2 + 4x10^1 + 5x10^0, how to perform some arithmetic operations to leave you with just the digit at position 5 (from the left) and output it to the screen? Thanks for the help!
Assuming you want to stick to arithmetic operations (and not strings), use the modulo operator with 10 to get the remainder of division by 10, i.e. the unit:
12345%10
output: 5
For an arbitrary number, you need to compute the position, you can use log10 and ceil:
from math import log10, ceil
N = 5
number = 1234567
number//10**(ceil(log10(number))-N)%10
output: 5

i need more decimal places for pi calculation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm trying to make a Pi calculator in python but I need more decimal places.
it would help a lot if someone edited my code and carefully explained what they did.
this is the code I'm using.
import math
d = 0
ans = 0
display = 0
while True:
display += 1
d += 1
ans += 1/d**2
if display == 1000000:
print(math.sqrt(ans*6))
display = 0
# displays value calculated every 1m iterations
output after ~85m iterations: (3.14159264498239)
I need more than 15 decimal places (3.14159264498239........)
You’re using a very slowly converging series for π²∕6, so you are not going to get a very precise value this way. Floating point limitations prevent further progress after 3.14159264498239, but you’re not going to get much further in any reasonable amount of time, anyway. You can get around these issues by some combination of
micro-optimising your code,
storing a list of values, reversing it and using math.fsum,
using decimal.Decimal,
using a better series (like this one),
using a method that converges to the value of π quickly, instead of a series (like this one),
using PyPy, or a faster language than Python,
from math import pi.
you could try with a generator:
def oddnumbers():
n = 1
while True:
yield n
n += 2
def pi_series():
odds = oddnumbers()
approximation = 0
while True:
approximation += (4 / next(odds))
yield approximation
approximation -= (4 / next(odds))
yield approximation
approx_pi = pi_series()
for x in range(10000000):
print(next(approx_pi))

Check if the length of the range divided by range element has no division remainder [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The code below shall show a specific comment if the number of elements in the array isn't integer-type number.
It works for dr=0.5 but not for dr=0.1 because print (4%0.1) returns 0.09999999999999978 instead of 0.
How can I change the code to get 4%0.1==0?
import math
limits_real=(-2,2)
dr=0.1
if (limits_real[1]-limits_real[0])%dr!=0:
print ('Inapropriate limits or elements')
It works for dr=0.5 but not for dr=0.1 because print (4%0.1) returns 0.09999999999999978 instead of 0.
Because floating point numbers have limitations that every programmer should know, see this:
https://docs.python.org/3/tutorial/floatingpoint.html
As showed at the end of above documentation, you can use decimal module, which works exacly right but is slower than normal floating point arihtmetics:
from decimal import Decimal
limits_real=(-2,2)
dr = Decimal("0.1")
if (limits_real[1] - limits_real[0]) % dr != 0:
print ('Inapropriate limits or elements')
Note that you should use a str while constructing the Decimal instance, do not use a float.
I found out only this solution :) At least it works
import math
limits_real=(-2,2)
dr=0.1
if (((limits_real[1] - limits_real[0]) * 1000) % (dr * 1000)) / 1000 != 0:
print ('Inapropriate limits or elements')

How do i figure out the multiple of a number python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
ok, I am studying python in my computing course and i have been challenged with designing a code which validates a GTIN-8 code, I have came to a hurdle that i can not jump. I have looked on how to find the equal or higher multiple of a 10 and i have had no success so far, hope you guys can help me!
Here is a small piece of code, i need to find the equal or higher multiple of 10;
NewNumber = (NewGtin_1 + Gtin_2 + NewGtin_3 + Gtin_4 + NewGtin_5 + Gtin_6 + NewGtin_7)
print (NewNumber)
The easiest way, involving no functions and modules, could be using floor division operator //.
def neareast_higher_multiple_10(number):
return ((number // 10) + 1) * 10
Examples of usage:
>>> neareast_higher_multiple_10(15)
20
>>> neareast_higher_multiple_10(21)
30
>>> neareast_higher_multiple_10(20.1)
30.0
>>> neareast_higher_multiple_10(20)
30
We can also make a generalized version:
def neareast_higher_multiple(number, mult_of):
return ((number // mult_of) + 1) * mult_of
If you need nearest lower multiple, just remove + 1:
def neareast_lower_multiple(number, mult_of):
return (number // mult_of) * mult_of
To find the nearest multiple, you can call both these functions and use that one with a lower difference from the original number.

Round negative float numbers to floats [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am trying to round some negative floating numbers, the format i want is like the below print/format way, not the round. The problem is that the print approach is not "clean", since it outputs a string with spaces, I got this code from another similar question here in Stackoverflow. The question is how to format/round the numbers like the print below. Thank you
theta = 0.33161255787892263
math = 0 + (1-0) * (1-math.cos(theta))**5
round(math,8) # Result: 4.8e-07 #
print("{:18.8f}".format(math)) # Result: ' 0.00000048' #
You say "I want the result of the print but in a float number not string" and "The result returns to a negative power floating point number, i want to keep the decimal format as the string". But you can't do that because you have no control over the internal representation of a float: they are all stored in a binary form of scientific notation. See the Wikipedia article on floating-point numbers for details.
So it doesn't matter whether you do
v = 0.00000048
or
v = 4.8e-07
both of those statements have an identical effect.
Note that many fractional numbers that terminate when written in decimal may repeat when written in binary. The only fractions that terminate when written in binary are of the form n / (2 ** b), where n and b are integers. Thus even an innocuous-looking number like 0.2 doesn't terminate when converted to binary. (See the Wiki link for a fuller explanation). Because of this issue it's generally not a good idea to round floating-point numbers until you've finished all calculations with them.
If you convert a string to float and back again it has to be converted from decimal to binary and back again. So such an operation shouldn't be used in an attempt to "clean up" a number because of the possible rounding errors at each conversion step.
Of course, sometimes you do need to apply rounding to a float that you are going to continue calculating with, but if so, you should proceed with caution and make sure you really do understand what you're doing to your data.
...
There are a few other strange things with the code you posted.
math = 0 + (1-0) * (1-math.cos(theta))**5
Firstly, you should not use the name of a module that you've imported as a variable name. After the above statement is executed math now refers to the result of the calculation, not the math module, so if you tried to do x = math.cos(0.5) you'd get an error. Similarly, don't use int, str, list, etc as variable names.
Secondly, the 0 + (1-0) * is virtually useless. So the above statement could be re-written as
result = (1 - math.cos(theta)) ** 5
And the whole code snippet would become
#! /usr/bin/env python
import math
theta = 0.33161255787892263
result = (1 - math.cos(theta)) ** 5
print round(result, 8)
print("{0:.8f}".format(result))
output
4.8e-07
0.00000048

Categories

Resources