IcanCwhatUsay
IcanCwhatUsay

Reputation: 81

Python, turn floats to integers

Ok, I know this question gets asked a lot, but often the responses are special case workarounds. I guess you could say that I'm trying to understand why this won't work in addition to how to get it to work.

# ---- Find Spring Rate ---- #
import math
import numpy as np
from pylab import plot, show, title, xlabel, ylabel, axis
import matplotlib as mpl
from matplotlib import pyplot as plt
'''
F = Load
D = mean dia of Coil
d = wire dia
Na = # of active coils
G = Shear Modulus 
'''
F = 30 #lbf   Assumed load 
D = 0.423 #in Measured 
d = 0.055 #in Measured
#N_a = 2.75 
G = 11.85*10**(6) #psi  # pg 526 Table 10-5 - Machine Theory Book
E = 29.0*10**(6) #psi   # pg 526 Table 10-5 - Machine Theory Book

X1 = []
Y1 = []

for N_a in range(1,6,0.025):
    y = (8*F*D**(3)*N_a)/(d**(4)*G) 
    k = (d**(4)*G)/(8*D**(3)*N_a)   
    K=(F//y)
    # print("N_a =", N_a)
    # print("y=", y)
    # print("k=", k)
    # print("K=", K)
    # print('\n')
    X1.append(N_a)
    Y1.append(k)

print("X1=", X1)
print("Y1=", Y1)

When I run this code, I get the following

Spring_Rate_Mk1.py", line 25, in <module>
    for N_a in range(1,6,0.025):
TypeError: 'float' object cannot be interpreted as an integer

What I've tried:

  1. np.arange() this seems to work, but it gives me values like these for X

X1= [1.0, 1.025, 1.0499999999999998, 1.0749999999999997, 1.0999999999999996, 1.1249999999999996, 1.1499999999999995, 1.1749999999999994, 1.1999999999999993, 1.2249999999999992, ... and so on]

  1. I've tried N_a = int(N) and also int in pretty much anywhere else I could think of to put it
  2. I've tried changing the division from / to //
  3. breaking the equations in to parts

    A = (d**(4)*G)
    B = (8*D**(3)*N_a)
    k = A/B
    

Upvotes: 1

Views: 72

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

np.arange works, you're just seeing the representation of the float.

And range doesn't work with a floating point step, but in your case that's easy to fix since the start & end points are actually integers.

Without arange, you could use an integer range and divide the value since 1/0.025 is 40 just multiply your bounds by 40 and apply the division just afterwards (using 40.0 just in case of python 2)

for N_a in range(40,240):
    N_a /= 40.0
    print(N_a)

prints:

1.0
1.025
1.05
1.075
1.1
1.125
1.15
1.175
1.2
1.225
1.25
1.275
1.3
1.325
1.35

and so on.... Dividing by a multiple of 10 and a power of 2 makes the result without representation error.

Upvotes: 2

Related Questions