python multiplying python float with numpy float - python

So I'm trying to do the following:
self.cashflows["Balance"] * self.assumptions["Default Rates"][current_period - 1]
where cashflows is a list with python floats and assumptions is a list with numpy floats.
I used numpy to fill the assumption vector and I am getting the following error when I try to multiply the two:
can't multiply sequence by non-int of type 'numpy.float64
I get the error but what would be my best course of action here?
thx

Depends on what you want to do. Do you want to multiply every item in the list self.cashflow["Balance"] with self.assumptions["Default Rates"][current_period - 1]? Then you can use some list comprehension:
result = [q * self.assumptions["Default Rates"][current_period - 1] for q in self.cashflow["Balance"]]
or convert your second argument to np.float:
result = self.assumptions["Default Rates"][current_period - 1]* np.asarray(self.cashflow["Balance"])
Otherwise, multiplying a whole list by N repeats that list N times. If thats what you want, cast your np.float64 to int.
EDIT: Added missing multiplication sign

Related

Consistent Type Error regarding converting a string to a float in Python

I am working on an assignment for an Introduction to Programming course and would like some direction as to what I am missing and why I continue getting the same TypeError. I am able to assign my strings however when I try to convert them to a float I end with a TypeError. I am pretty new to programming and coding in general so please don't be too harsh. I understand that it is probably something really obvious.
I have attempted to define the variable and convert it to a float from a string both prior to the calculation when I was setting up my inputs as well as during calculation of what the algorithm is attempting to execute.
enter_quizzes_weight = input("quizzes weight")
enter_quizzes_average = input('quizzes average')
quizzes_grade = float(enter_quizzes_weight * enter_quizzes_average)
The expected result is supposed to be the output of converting the strings to floats and then multiplying enter_quizzes_weight and enter_quiz_average however the actual result ends in the following error,
"TypeError: can't multiply sequence by non-int of type 'str'"
quizzes_grade = float(enter_quizzes_weight * enter_quizzes_average)
That code multiplies two variables and then converts the result to a float.
But you're doing the float conversion too late, because those two variables are strings, and you can't multiply strings.
You need to convert the variables to floats before multiplying:
quizzes_grade = float(enter_quizzes_weight) * float(enter_quizzes_average)
This should do:
enter_quizzes_weight = float(input("quizzes weight"))
enter_quizzes_average = float(input('quizzes average'))
quizzes_grade = (enter_quizzes_weight * enter_quizzes_average)
You're turning the strings you get from input("quizzes weight") and input('quizzes average') into floats, and then you multiply them

sum in python where list of list are in exponential

I would like to write the following summation in python
The coefficients are given as the following list
cn=[1.2,0.4,0.6]
vn=[1e-6,5e-5,1e-6]
gn=[4.5e3,6.5e3,9e3]
t=np.linspace(0,10,100)
I tried the following
import numpy as np
cn=[1.2,0.4,0.6]
vn=[1e-6,5e-5,1e-6]
gn=[4.5e3,6.5e3,9e3]
t=np.linspace(0,10,100)
yt=np.sum(cn *np.exp(-vn*(t-gn)**2))
but am getting the error
TypeError: bad operand type for unary -: 'list'
I would like to know where am getting it wrong or how to do this task
This run:
import numpy as np
cn=np.array([1.2,0.4,0.6])
vn=np.array([1e-6,5e-5,1e-6])
gn=np.array([4.5e3,6.5e3,9e3])
t=np.linspace(0,10,3)
yt=np.sum(cn * np.exp(-vn * (t - gn)**2))
Transform lists into numpy arrays
Make sure the matrix / array sizes are compatible, (ie. You can't add arrays of different lengths)
Example:
Add int to python list:
cn=[1.2,0.4,0.6]
cn+1
# output: TypeError: can only concatenate list (not "int") to list
Add int to numpy array:
cn=np.array([1.2,0.4,0.6])
cn+1
# output: array([2.2, 1.4, 1.6])
Add numpy arrays with different dimensions:
cn = np.arange(1,3)
t = np.arange(1,100)
cn + t
# output: ValueError: operands could not be broadcast together with shapes (2,) (99,)
Add numpy arrays with the same dimensions:
cn = np.arange(1,3)
t = np.arange(3,5)
cn + t
# output: array([4, 6])
Here is a lazy way of fixing it:
yt=np.sum(cn *np.exp(0-vn*(np.c_[t]-gn)**2), 1)
^ ^------^ ^-^
I've highlighted the changes. The most important change is the np.c_ which does two things:
It converts t to array
It makes t a column vector
1) serves as a "germ" for converting all the other lists to arrays via overloaded arithmetic operators.
Exception: the unary - in front of vn hits vn before it gets the chance to become an array. We put a zero in front the - to make it binary, thereby reducing it's precedence and closing the array coercion chain. This is not the most obvious fix but the one involving the least typing.
2) separates the time dimension from the summation dimension which is likely the correct interpretation. We have to add an eplicit axis argument to the sum which is the 1 we inserted at the very end of the expression.
If found two issues which I fixed but I am not sure is what you intended.
you don't need to convert the list to numpy array because you can perform arithmetic array between ndarray and list which will result ndarray.
Two error found are
1. shape of t was not matching with other arrays
2. you were trying to negate python list which doesn't support it
Also as you haven't put tn in your mathematical expression of summation above so I doubt it you want the length of t to be 3
import numpy as np
cn=[1.2,0.4,0.6]
vn=[1e-6,5e-5,1e-6]
gn=[4.5e3,6.5e3,9e3]
t=np.linspace(0,10,3) # shape of t what 100 and not matching with other arrays
yt=np.sum(cn *np.exp(-(vn*(t-gn)**2))) # -(vn*(t-gn)**2)) wasn't wrapped in brackets

How can we take user input for long integers?

I am appending values in an array which should contain long integers.
So, how can I take user inputs for it, as overflow error is shown.
from array import *
import math
n = int(input())
arr = array('l',[])
for i in range (n):
x = int(input())
arr.append(x)
There is no problem with the input()
Your problem is:
python can handle integers of infinte size, C's datatype long cant:
https://en.wikipedia.org/wiki/C_data_types#Basic_types
arr = array('l',[])
If you don't need to use datatypes from C, just use a list.
Else you can look for a datatype whoch can handle bigger numbers.

How to convert cartesian coordinates to complex numbers in numpy

I have an array of Cartesian coordinates
xy = np.array([[0,0], [2,3], [3,4], [2,5], [5,2]])
which I want to convert into an array of complex numbers representing the same:
c = np.array([0, 2+3j, 3+4j, 2+5j, 5+2j])
My current solution is this:
c = np.sum(xy * [1,1j], axis=1)
This works but seems crude to me, and probably there is a nicer version with some built-in magic using np.complex() or similar, but the only way I found to use this was
c = np.array(list(map(lambda c: np.complex(*c), xy)))
This doesn't look like an improvement.
Can anybody point me to a better solution, maybe using one of the many numpy functions I don't know by heart (is there a numpy.cartesian_to_complex() working on arrays I haven't found yet?), or maybe using some implicit conversion when applying a clever combination of operators?
Recognize that complex128 is just a pair of floats. You can then do this using a "view" which is free, after converting the dtype from int to float (which I'm guessing your real code might already do):
xy.astype(float).view(np.complex128)
The astype() converts the integers to floats, which requires construction of a new array, but once that's done the view() is "free" in terms of runtime.
The above gives you shape=(n,1); you can np.squeeze() it to remove the extra dimension. This is also just a view operation, so takes basically no time.
How about
c=xy[:,0]+1j*xy[:,1]
xy[:,0] will give an array of all elements in the 0th column of xy and xy[:,1] will give that of the 1st column.
Multiply xy[:,1] with 1j to make it imaginary and then add the result with xy[:,0].

Python error 'numpy.float64' object cannot be interpreted as an integer

I'm using Python3.x.
The bricks = [] the data is dataframe single element array which contains number and some negative numbers
for delta in data:
if delta > 0:
bricks.extend([1] * delta)
else:
bricks.extend([-1] * abs(delta))
The above code throws error, without affecting the outcome how to correct the code which will run without errors
The error here is:
bricks.extend([1] * delta) TypeError: 'numpy.float64' object cannot be
interpreted as an integer
Note :Community, before giving negative numbers, marked as duplicate provide a solution and then mark as you wish.
I think you should try
bricks.extend([1. * delta])
Considering that your "delta" is a simple value(numpyFloat or something like that) and you want to extend the list with a list of 1 value.

Categories