111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
a=(0.5 + 2.5*(k %2))*k + k % 2
This implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
a=(1 + 5*(k %2))*k//2 + k % 2
It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.
What exactly is going wrong?
Edit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.
As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.
When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:
>>> a = 111111111111111111111111111111111111111
>>> a + 1
111111111111111111111111111111111111112L
>>> str(a)
'111111111111111111111111111111111111111'
>>> int(a)
111111111111111111111111111111111111111L
I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!
Another way to avoid numerical errors in python is to use Decimal type instead of standard float.
Please refer to official docs
Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.
Related
e = str(2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274)
print(e)
Output:
2.718281828459045
Screenshots: here and here.
Why does the code only print out the first few characters of e instead of the whole string?
A string str has characters, but a number (be it an int or a float) just has a value.
If you do this:
e_first_100 = '2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274'
print(e_first_100)
You'll see all digits printed, because they are just characters in a string, it could have also been the first 100 characters from 'War and Peace' and you would not expect any of that to get lost either.
Since 'e' is not an integer value, you can't use int here, so you'll have to use float, but Python uses a finite number of bits to represent such a number, while there's an infinite number of real numbers. In fact there's an infinite number of values between any two real numbers. So a clever way has to be used to represent at least the ones you use most often, with a limited amount of precision.
You often don't notice the lack of precision, but try something like .1 + .1 + .1 == .3 in Python and you'll see that it can pop up in common situations.
Your computer already has a built-in way to represent these floating point numbers, using either 32 or 64 bits, although many languages (Python included) do offer additional ways of representing floats that aren't part of the way your computer works and allow a bit more precision. By default, Python uses these standard representations of real numbers.
So, if you then do this:
e1 = float(e_first_100)
print(e1)
e2 = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
print(e2)
Both result in a value that, when you print it, looks like:
2.718281828459045
Because that's the precision up to which the number is (more or less) accurately represented.
If you need to use e in a more precise manner, you can use Python's own representation:
from decimal import Decimal
e3 = Decimal(e_first_100)
print(e3)
That looks promising, but even Decimal only has limited precision, although it's better than standard floats:
print(e2 * 3)
print(e3 * Decimal(3))
The difference:
8.154845485377136
8.154845485377135706080862414
To expand on Grismar's answer, you don't see the data because the default string representation of floats cuts off at that point as going further than that wouldn't be very useful, but while the object is a float the data is still there.
To get a string with the data, you could provide a fixed precision to some larger amount of digits, for example
In [2]: e = format(
...: 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274,
...: ".50f",
...: )
In [3]: e
Out[3]: '2.71828182845904509079559829842764884233474731445312'
which gives us the first 50 digits, but this is of course not particularly useful with floats as the loss of precision picks up the further you go
So, I have to create a python script that given 2 fractions and an operand will print the result of the operation. This was intended to be solved by firstly asking for one fraction and saving it into a variable, then ask for another fraction and lastly ask for the operand. But out of curiosity I've tried to give this problem a different point of view.
My idea was to ask for the full operation and save the input string into a variable, then with the function exec() I could get the decimal result of the given operation, finally to deal with decimals my idea was to multiply by 10 to the power of the number of decimal digits and then dividing by 10 to that same power, this way I could have a fraction as a result. So I went on to code and managed to program this out, my only issue is that the number of decimal digits is limited so normally the result that my script returns is a very big fraction that is very close to what the real fraction is. So I was wondering if there is any workaround for this. Here is my code and an example for further explanation:
op = input('Enter operation: ')
try:
exec('a = ' + op)
except:
print('Invalid operation')
def euclides(a, b):
while a != 0 and b != 0:
if a < b: b = b%a
else: a = a%b
if a == 0: return b
elif b == 0: return a
print(f'{int(a*10**len(str(a).split(".")[1])/euclides(a*10**len(str(a).split(".")[1]),10**len(str(a).split(".")[1])))}/{int(10**len(str(a).split(".")[1])/euclides(a*10**len(str(a).split(".")[1]),10**len(str(a).split(".")[1])))}')
EXAMPLE:
op input => 4/3+5/7
Result of script => 5119047619047619/2500000000000000 = 2.04761904761
Result I'm looking for => 43/21 = 2.047619 period
Thank you for your help in advance
What are your constraints as to what standard or add-on modules you can use? Without taking into account constraints you haven't specified, there are much better ways to go about what you're doing. Your problem seems to be summed up by "the result that my script returns is a very big fraction" and your question seems to be "I was wondering if there is any workaround for this?". There are a number of "work arounds". But it's pretty hard to guess what the best solution is for you as you don't tell us what tools you can and can't use to accomplish your task.
As an example, here's an elegant solution if you can use regular expressions and the fractions module, and if you can assume that the input will always be in the very strict format of <int>/<int>+<int>/<int>:
import re
import fractions
op = input('Enter operation: ')
m = re.match(r"(\d+)/(\d+)\+(\d+)/(\d+)", op)
if not m:
raise('Invalid operation')
gps = list(map(int, m.groups()))
f = fractions.Fraction(gps[0], gps[1]) + fractions.Fraction(gps[2], gps[3])
print(f)
print (float(f))
print(round(float(f), 6))
Result:
43/21
2.0476190476190474
2.047619
This answers your current question. I don't, however, know if this violates the terms of your assignment.
Could just turn all natural numbers into Fractions and evaluate:
>>> op = '4/3+5/7'
>>> import re, fractions
>>> print(eval(re.sub(r'(\d+)', r'fractions.Fraction(\1)', op)))
43/21
Works for other cases as well (unlike the accepted answer's solution, which only does the sum of exactly two fractions that must be positive and must not have spaces), for example:
>>> op = '-1/2 + 3/4 - 5/6'
>>> print(eval(re.sub(r'(\d+)', r'fractions.Fraction(\1)', op)))
-7/12
Checking:
>>> -7/12, -1/2 + 3/4 - 5/6
(-0.5833333333333334, -0.5833333333333334)
Scratching my head at what seems like the simplest thing ever.
I am working on a polynomial calculator and have been testing it with some values, but python is not adding these two values the way it needs to be.
ans_2 = (-0.423604188255 + 0.42368554704)
print("Ans 2 = : " + str(ans_2))
I am getting this answer:
Ans 2 = : 8.1358785e-05
But I should be getting an answer like this:
=0.00009
Is there something I am doing wrong?
The value 8.1358785e-05 is scientific notation for the value .000081358785. The print function automatically converts to scientific notation for floats under a certain value.
If you want it to print out the value you're looking for, you need to format the string to tell the print function exactly what you're looking for. You can do that like this
In [11]: ans_2 = (-0.423604188255 + 0.42368554704)
In [12]: print("Ans 2 = : {:.7f} ".format(ans_2))
Ans 2 = : 0.0000814
This will format the string to include seven digits after the decimal.
The value 8.1358785e-05 is just another representation of 0.000081358785.
Whenever you see 'e' in your number means that your value was multiplied by 10 to power of anything that goes after 'e'.
In your case it will be:
8.1358785 * 10 ^ (-5) = 0.000081358785
For more info look there
Possibly you are overlooking that there is -ve sign before the first number. That's why you seem to expect the function to return 0.847289735295 (sum of absolute values of operands) instead of the correct answer (their difference according to their sign)
I am trying to write a program in python 2.7 that will first see if a number divides the other evenly, and if it does get the result of the division.
However, I am getting some interesting results when I use large numbers.
Currently I am using:
from __future__ import division
import math
a=82348972389472433334783
b=2
if a/b==math.trunc(a/b):
answer=a/b
print 'True' #to quickly see if the if loop was invoked
When I run this I get:
True
But 82348972389472433334783 is clearly not even.
Any help would be appreciated.
That's a crazy way to do it. Just use the remainder operator.
if a % b == 0:
# then b divides a evenly
quotient = a // b
The true division implicitly converts the input to floats which don't provide the precision to store the value of a accurately. E.g. on my machine
>>> int(1E15+1)
1000000000000001
>>> int(1E16+1)
10000000000000000
hence you loose precision. A similar thing happens with your big number (compare int(float(a))-a).
Now, if you check your division, you see the result "is" actually found to be an integer
>>> (a/b).is_integer()
True
which is again not really expected beforehand.
The math.trunc function does something similar (from the docs):
Return the Real value x truncated to an Integral (usually a long integer).
The duck typing nature of python allows a comparison of the long integer and float, see
Checking if float is equivalent to an integer value in python and
Comparing a float and an int in Python.
Why don't you use the modulus operator instead to check if a number can be divided evenly?
n % x == 0
Looking to format a output to show a very small number..
a= 6500
b= 3600
c=.000900
d= int((b/a)-c)
print d
Answer comes out to be zero, but looking for the .###### numbers after the .
sorry try this
Looks like you got bitten by integer division in python 2.x.
>>> a= 6500
>>> b= 3600
>>> c=.000900
>>> from __future__ import division
>>> print b/a - c
0.552946153846
There may be two issues with your calculation:
If you're using Python 2, division using / between two integers will always be an integer also. This will discard the fractional part of the calculation, which can be unexpected. One fix for this is to force one of the values to be a float value (e.g. float(b)/a). An alternative is to put at the top of your file from __future__ import division, which tells Python to use the Python 3 semantics for division (you'll only get an integer from integer division if the result is an exact integer).
The second issue seems to be about formatting a floating point value. First you seem to want only the fractional part of the value (not the integer part). Usually the best option is to simply subtract the integer part of the value:
d = someFloatingPointValue()
d_frac = d - int(d)
Next, to get a string to output (where you want several decimal places, but not a huge number of them), you probably want to explore Python's string formatting operations:
d = someFloatingPointValue()
d_to4decimalPlaces = "{:.4f}".format(d)