Why subtract a value from itself (x - x) in Python? - python

In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do?
t,w = asarray(t), asarray(duty)
w = asarray(w + (t-t))
t = asarray(t + (w-w))
source

I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.

Related

How to calculate complex simultaneous equations in python?

I need to obtain three complex numbers from a set of three equations which is part of an error correction procedure for a set of S-parameters.
import numpy as np
G_A1 = -1 + 0j
G_A2 = 0 + 0j
G_A3 = 1 + 0j
G_M1 = -0.5323 - 0.0163j
G_M2 = -11.1951 - 37.7373j
G_M3 = 0.5528 + 0.1621j
a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3,G_M3)]])
b = np.array([G_M1,G_M2,G_M3])
x = np.linalg.solve(a, b)
print(x)
This gives me the error
a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3,G_M3)]])
TypeError: a float is required
I thought I might as well try to convert the complex values to float but then I get this error.
G_M1 = float(-0.5323 - 0.0163j)
TypeError: can't convert complex to float
If complex values cannot be converted to float, what alternative method should I be using here?
You have a typo in the last entry of last row which makes it a tuple
(-G_A3,G_M3)
and leads to a TypeError as an element. If you correct that the problem goes away. You also don't need to put parentheses around the expressions in this case anyways.

Convert a scipy interp1d array to a float value in Python

in my current project I have currently a conversion issue:
In a first step I am interpolating two lists with scipy interp1d.
f_speed = scipy.interpolate.interp1d(t, v, 'cubic')
After that I want to get one specific point in this function. This value is now an array from scipy with only one value in it.
currentSpeed = f_speed(tpoint)
# result: array(15.1944)
As a last step I want to calculate other values with the value from the interpolated function, but I only get 0 as a value. There is no Error at all.
real_distance = currentSpeed * (1/15) # some calculations
# result: 0, all results with further calculations are zero
I need a conversion from scipy array to a regular float value to proceed my calculations. Is there any function to do this?
I tried several things like V = currentSpeed[0], or .tolist from numpy (not possible in scipy)...
Thanks for your help in advance!!
You did not specify which Python version you're using, but if you're using Python 2.7, then operator / stands for integer division. It means that 1/15 will produce 0. Multiplying something with this results will end up being 0, regardless of how you access array values.
To solve the problem, make sure at least one operand is a float number.
result1 = 1/15 # Produces 0
result2 = 1.0/15 # Produces 0.06666666666666667
If you apply this to your code, you should use
real_distance = currentSpeed * (1.0/15)
Are you using Python 2? If so the problem is the division.
Integer division will result in an integer so 1/15 will result in 0.
Try 1.0/15 instead. By using 1.0 you make it explicitly a float an then the result will be as expected.

Is there anyway in C that will automatically detect the data type of the inserted value and then will store the value in that particular data type?

If we want to store an integer number we use %d, if we want to store decimal number we use %f. So, I am wondering if there is anyway in C that will automatically detect the data type of the inserted value. Consider the following program is written using python:
a = 2
b = 3.5
c = a + b
print(c)
the output will be 5.5. So it is really great.
The purpose is that i want to write a code that will find out the value of x and y (just two unknown variable) using cross multiplication method. For a clear concept look at the following equation:
(a1*x)+(b1*y)=c1;
(a2*x)+(b2*y)=c2
From this type of equation i want to find out the values of x and y.So, first the program will ask the user to input some value for a1, a2, b1, b2 and c1, c2. Then it will perform the operation. That's fine.
Now, If i define the variable type as integer then user will not be able to perform the operation with fraction value. Likewise, if i define the variable type as float/double the user won't be able to perform the operation with integer number. I mean, the user will not get expected answer.
So, my question is, Is there anything in C, that will automatically detect the data type and then will store it in that particular data type and finally after calculating the result, it will give the result in appropriate form. if the result is integer it will print out integer or if the result is fraction, the output will be decimal number.
Automatically? No. That's one of the reasons why people use Python instead of C - it has polymorphism (the ability to perform the same operations on different types), but C doesn't.
In C you would need separate code branches to deal with different types.
In C you need to decide beforehand what data type you are using.
In this case, I would recommend using double and if you need to, have an if when printing.
Most major C implementations use IEEE754 floating point.
One of the implications of IEE754 is that if any intermediate step results in a fractional value then the result will likely not be exact.
Example:
double x = 1.0/3;
x *= 3;
x == 1.0; /* Evaluates to false if IEEE754 is used */
Even if you get a function to print the output like "print" function in python, you still need to decide the datatype of the user input in scanf.
According to the requirement, you can actually declare the data type of the inputs as float/double and print the output with %g.
float p = 2, q = 3.5;
printf("%g", p+q);
%g will remove the trailing zeros and you will get the require output.

Subtracting two numbers of any base between 2 and 10

For two numbers x and y that are base b, does this work for subtracting them? The numbers are given in string format and 2 <= b <= 10.
def n2b(n, b): # function to convert number n from base 10 to base b
if n == 0:
return 0
d = []
while n:
d.append(int(n % b))
n /= b
return ''.join(map(str,d[::-1]))
x = int(x,b) # convert to integers in base 10
y = int(y,b)
z = x - y
z = n2b(z,b) # convert back to base b, still in integer form
You have some confusion about how integers work in python. As the comments above say: python always stores integers in binary form and only converts them to a base when you print them. Depending on how you get x and y and how you need to give back z the code needs to be different
Situation 1: x, y and z are all integers
In this case you only need to do
z = x - y
And you're done.
Situation 2: x, y and z are all strings
In this case you first need to convert the strings into integers with the right base. I think that's your case, since you already deal with int(x, b) which is correct to transform a string into an integer (e.g. int("11", 2) gives 3 (integer represented in base 10). I would advice you to reform your code into something like this:
x_int = int(x, b)
y_int = int(y, b)
z_str = n2b(x_int - y_int, b)
In your code x is first a string and then an integer, which is bad practice. So e.g. use x_int instead of x.
Now it comes down to if your n2b function is correct. It looks good from the distance, although you're not handling signs and bases bigger than 10. There is a broadly accepted convert integer to base b answer so you might take this to be sure.
This is exactly the problem I just ran into in the google foobar challenge (which I suspect is the same source of ops problem). Granted its years later and op has no use for my answer but someone else might.
The issue
The function op used looked a lot like a copy and paste of this provided by the accepted answer but slightly modified (although I didn't look to closely).
I used the same function and quickly realized that I needed my output to be a string. Op appears to have realized the same thing based on the return statement at the end of the function.
This is why most of the test cases passed. Op did almost everything right.
See, the function begins with
if n==0:
return 0
One of the test cases in the foobar challenge uses 0 as the input. Its an easy line to miss but a very important one.
Solution
When I was presented this problem, I thought about the possible outlier cases. 0 was my first idea (which turned out to be right). I ran the program in vscode and would ya look at that - it failed.
This let me see the error message (in my case it was a list rather than int but op would have received a similar error).
The solution is simply changing return 0 to return '0' (a string rather than int)
I wasn't super excited to write out this answer since it feels a bit like cheating but its such a small detail that can be so infuriating to deal with. It doesn't solve the challenge that foobar gives you, just tells you how to get past a speed bump along the way.
Good luck infiltrating commander lambda's castle and hopefully this helps.

Convert 2-d array of strings to float in python_removing scientific notation

How can I convert scientific notations to the original format when I use numpy.astype in x array? Here's my code:
with open ('outfile.csv', 'r') as infile:
reader = csv.reader(infile)
reader_list = list(reader)
reader_array = array(reader_list)
x = reader_array[:,5].astype(np.float)
#original array:
print reader_array[:,5]
#converted to float
print x
#original array:
['-0.00041955436132607246' '-0.00036612800229292086' '0.00022313364860991641' ..., '73.418371245304215' '73.417384428365267' '73.416718169781149']
#converted to float
[ -4.19554361e-04 -3.66128002e-04 2.23133649e-04 ..., 7.34183712e+01 7.34173844e+01 7.34167182e+01]
To be more specific, I want to convert array of strings to floats, but keep the same format as the original array, and do some analysis on it:
#find row number of max value in column 1: (This piece works fine)
max_index = where(reader_array[:,1] == max(reader_array[:,1]))
#take last element in column 5: (This one is also fine)
total_ = (reader_array[(len(reader_array[:,5])-1),5])
#find row number where element in column 5 is equal to 0.1*total_: (here's the problem!)
0.1_index = where((reader_array[:,5]) == (total_)*0.1)
So I think changing the strings to floats but with the same format as the original array allows multiplying array members by another float (0.1 here).
Please note that the value (0.1*total_) may not match any of the rows values in column 5, which I have to think how to solve. But I cannot progress without being able to compare rows with (0.1*total_).
I appreciate if someone can give a hint how to approach please.
You're intrinsically limited by the fact that floating point numbers are stored using IEEE 754. You can't have arbitrary precision floating points, so in your case, you can't expect them to necessarily be exactly the same as a string representation.
However, in your case, the more pressing issue is that want to compare a string to a float, so of course they are going to be different. Python is dynamically, but strongly typed.
Given both the above points, you need to better define your problem. Why do you need to compare with an array of strings? (what does this even mean!?)
Can you test for closeness rather than equality once you have your data types sorted out (e.g. using numpy.close)?

Categories

Resources