How to assign a variable a float times an integer - python

Q1 should be able to contain 1.602*10^-19 and Q2: -1.602*10^-19
Instead it gives me a value error: ValueError: invalid literal for float().
What am I doing wroing. I am a beginner by the way.
import os
Clear = lambda: os.system("cls")
Clear()
Q1 = float(raw_input("What's Q1?\n"))
Q2 = float(raw_input("What's Q2?\n"))
r = float(raw_input("What's radius?\n"))
def calc(Q1, Q2, r):
k = 8.99*10**9
return((k((Q1) * Q2))/r**2)
print(calc(Q1, Q2, r))

You did not say what input you are using or what line you are getting the error, so I am going to assume you are trying to do float("1.602*10^-19").
This is not a valid argument, to need to use a different notation to meet the required format:
float("1.602e-19")

Did you input 1.602*10^-19?
If so, please note the correct format is 1.602e-19

Related

Converting list from string to int but there's a catch

I'll start off by saying that I don't know much about programming and I tried searching for answers but I didn't even know what to type in the search engine. So here goes.
class Point:
def __init__ (self, x, y):
self.x = x
self.y = y
def __str__ (self):
return "Members are: %s, %s" % (self.x, self.y)
I have this class which represents a point with its x and y coordinate.
I have a list points = [] and if I manually append a point to that list e.g. points.append(Point(-1.0, 3)) the output returns (-1.0, 3) I'm doing some calculations with these points but I don't think it matters if I put the code for that here.
Things get tricky because I have to input the numbers from a file. I already added them to another list and appended them using a loop. The problem is that the list is in str and if I convert it into int I get an error because of the decimal .0 It says in my assignment that I have to keep the same format as the input.
The thing I don't understand is how does it keep the decimal .0 when I input it like this points.append(Point(-1.0, 3)) and is it possible to get the same output format with numbers from a file.
I tried converting it to float but then all the coordinates get decimal places.
You can use this code to convert the inputs appropriately, with this try-catch mechanism, we first try int, then if we didn't successful, we continue with float.
def float_or_int(inp):
try:
n = int(inp)
except ValueError:
try:
n = float(inp)
except ValueError:
print("it's not int or float")
return n
input_1 = '10.3'
input_2 = '10.0'
input_3 = '10'
res1 = float_or_int(input_1)
res2 = float_or_int(input_2)
res3 = float_or_int(input_3)
print(res1, type(res1)) # 10.3 <class 'float'>
print(res2, type(res2)) # 10.0 <class 'float'>
print(res3, type(res3)) # 10 <class 'int'>
I don't know how your inputs stored in the file/another list you are reading, but you get the idea how to parse a single input.
You could use this:
proper_points = []
for x,y in points:
float_x = float(x)
int_y = int(y)
coords = proper_points.append((x,y))
For your calculations, you could use the proper_points list instead of points
Man, do not reinvent the wheel. If you need to import data from file you can use numpy for example and the function loadtxt. https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
I do not understand how your file is made and the format of the coordinate. In the bunch of code points.append(Point(-1.0, 3)) the first number is a float the second one is an integer. Which format do you want?
For example in file.dat you have the x,y positions:
1 1
2 3
4 5
where the first column is the x position and the second one represents y. Then you can use this code
import numpy as np
points = np.loadtxt('file.dat', dtype = 'int')
in points you have all the positions inside the file and you can just use slicing to access them.

KeyError with a poisson process using pandas

I am trying to create a function which will simulate a poison process for a changeable dt and total time, and have the following:
def compound_poisson(lamda,mu,sigma,dt,T):
points = pd.Series(0)
out = pd.Series(0)
inds = simple_poisson(lamda,dt,T)
for ind in inds.index:
if inds[ind+dt] > inds[ind]:
points[ind+dt] = np.random.normal(mu,sigma)
else:
points[ind+dt] = 0
out = out.append(np.cumsum(points),ignore_index=True)
out.index = np.linspace(0,T,int(T/dt + 1))
return out
However, I receive a "KeyError: 0.010000000000000002", which should not be in the index at all. Is this a result of being lax with float objects?
In short, yes, it's a floating point error. It's quite hard to know how you got there, but probably something like this:
>>> 0.1 * 0.1
0.010000000000000002
Maybe use round?

extract number from exponent in Python

Hi everyone / Python Gurus
I would like to know how to accomplish the following task, which so far I've been unable to do so.
Here's what I have:
Q1 = 20e-6
Now this is an exponential number that if you print(Q1) as is it will show: 2e-5 which is fine. Mathematically speaking.
However, here's what I want to do with it:
I want Q1 to print only the number 20. And based on the whether this is e-6 then print uC or if this e-9 the print nC.
Here's an example for better understanding:
Q1=20e-6
When I run print(Q1) show: 20uC.
Q2=20e-9
When I run print(Q2) show: 20nC.
Can you please help me figure this out?
just replace the exponent using str.replace:
q1 = 'XXXXXX'
q1 = q1.replace('e-9', 'nC').replace('e-6', 'uC')
print(q1)
I recommend you using si-prefix.
You can install it using pip:
sudo pip install si-prefix
Then you can use something like this:
from si_prefix import si_format
# precision after the point
# char is the unity's char to be used
def get_format(a, char='C', precision=2):
temp = si_format(a, precision)
try:
num, prefix = temp.split()
except ValueError:
num, prefix = temp , ''
if '.' in num:
aa, bb = num.split('.')
if int(bb) == 0:
num = aa
if prefix:
return num + ' ' + prefix + char
else:
return num
tests = [20e-6, 21.46e05, 33.32e-10, 0.5e03, 0.33e-2, 112.044e-6]
for k in tests:
print get_format(k)
Output:
20 uC
2.15 MC
3.33 nC
500
3.30 mC
112.04 uC
You can try by splitting the string:
'20e-9'.split('e')
gives
['20', '-9']
From there on, you can insert whatever you want in between those values:
('u' if int(a[1]) > 0 else 'n').join(a)
(with a = '20e-9'.split('e'))
You can not. The behaviour you are looking for is called "monkey patching". And this is not allowed for int and float.
You can refer to this stackoverflow question
The only way I can think of is to create a class that extends float and then implement a __str__ method that shows as per your requirement.
------- More explanation -----
if you type
Q1 = 20e-6
in python shell and then
type(Q1)
your will get a
float
So basically your Q1 is considered as float by python type system
when you type print(Q1)
the _str__ method of float is called
The process of extending core class is one example of "monkey patch" and that is what I was refereing to.
Now the problem is that you can not "monkey patch" (or extend if you prefer that) core classes in python (which you can in some languages like in Ruby).
[int, float etc are core classes and written in C for your most common python distribution.]
So how do you solve it?
you need to create a new class like this
class Exponent(float):
def init(self, value):
self.value = value
def __str__(self):
return "ok"
x = Exponent(10.0)
print(x) ==> "ok"
hope this helps

Python/Numpy: Division gives me an unexpected deprecation-Warning

Im reading data from a csv, then looping it, then I want to divide it by the mean value to normalize it but getting a warning. The code is:
A = genfromtxt("train.txt", delimiter=';', skip_header=1)
lowid = A[:,1].min(axis=0)
highid = A[:,1].max(axis=0)
X = []
Y = []
for i in np.arange(lowid, highid):
I = A[A[:,1] == i][:, [0,2,3]]
meanp = np.mean(I[:,1]);
meanq = np.mean(I[:,2]);
for j in np.arange(I[:,0].min(axis=0)+2, I[:,0].max(axis=0)):
weekday = int(I[j,0]) % 7
# NORMALIZE:
P = I[j,1] / meanp
pP = I[j-1,1] / meanp
ppP = I[j-2,1] / meanp
X.append([weekday, P, pP, ppP])
Y.append(I[j,2])
the train.txt looks like this:
day;itemID;price;quantity
1;1;4.73;6
1;2;7.23;0
1;3;10.23;1
1;4;17.9;0
1;5;1.81;1
1;6;12.39;1
1;7;7.17;1
1;8;7.03;0
1;9;13.61;0
1;10;36.45;1
1;11;24.67;0
1;12;12.04;0
1;13;11.85;0
The warnings:
weekday = int(I[j,0]) % 7
DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
P = I[j,1] / meanp
DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
pP = I[j-1,1] / meanp
DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
ppP = I[j-2,1] / meanp
DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
Y.append(I[j,2])
DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
What is the problem?
Thanks
EDIT Okay that was a pretty fast fix myself:
The j has got to be of integer type. I fixed it like this:
for j in range(int(I[:,0].min(axis=0))+2, int(I[:,0].max(axis=0))):
good solution like this? Im new to python...
Okay that was a pretty fast fix myself: The j has got to be of integer type.
I fixed it like this:
for j in range(int(I[:,0].min(axis=0))+2, int(I[:,0].max(axis=0))):
using the python range function OR explicitely defining the data-type for arange like this (thanks #Davidmh):
for j in np.arange(I[:,0].min(axis=0)+2, I[:,0].max(axis=0), dtype=np.int):

Binary To String Conversion

I'm relatively new to python and I'm trying to design a program that takes an input of Binary Data and Converts it to a String of Text. I have the following so far but keep getting the following error: TypeError: unsupported operand type(s) for &: 'str' and 'int' Can anyone see where I'm going wrong? And, if so, advise how to fix it?
a = int(input("please enter the binary you want to convert: "))
for str in a:
g = [~(chr(str)&~240)|(e&~240)]
f = 86
e = 231
d = bin(chr(str))
b = (str)
j=(b)
print(j)
There is quite a lot wrong with what you're doing; I'm not sure how you get the error you claim to have, given the other errors in the posted code. In order of reading the function:
Don't call your own variables str, it prevents you from accessing the built-in of the same name. Also, that variable either isn't a str, or causes a TypeError on chr(str).
You can't iterate over an integer for x in y:; this is also a TypeError.
(The error you report) chr(str) returns a string of length one. This is not a valid operand type for &, hence TypeError.
Another operand, e, has not yet been defined, so that will be a NameError.
Irrespective of that, you never use g again anyway.
Or f - what's that even for?
Now e is defined!
bin(chr(str)) will never work - again, chr returns a string, and bin takes a number as an argument.
b = (str) works, but the parentheses are redundant.
Same with j = (b), which is also not indented far enough to be in the loop.
Neither is print(j).
It is not clear what you are trying to achieve, exactly. If you gave example inputs (what format is the "Binary Data"?) and outputs (and what "String of Text" do you want to get?) along with your actual code and the full error traceback this might be easier.
Edit
With the information provided in your comment, it appears that you are trying to reverse these operations:
a = input("please enter the text you want to hide: ")
for ch in a:
## b = (ch) # this still doesn't do anything!
c = ord(ch)
## d = bin(c) # and d is never used
## e = 231 # e is only used to calculate g
f = 86
## g = (((c&240) >> 4)|(e&240)) # which is also never used
h = (((c&15)|(f&240)))
j = bin(h)
print(j)
This produces, for example (a == 'foo'):
0b1010110
0b1011111
0b1011111
However, to convert the input '0b1010110' to an integer, you need to supply int with the appropriate base:
>>> int('0b1010110', 2)
86
and you can't iterate over the integer. I think you want something like:
data = input("please enter the binary you want to convert: ")
for j in data.split():
h = int(j, 2)
...
where the input would be e.g. '0b1010110 0b1011111 0b1011111', or just do one at a time:
h = int(input(...), 2)
Note that, as the function is reversed, you will have to define f before trying to go back through the bitwise operation.

Categories