2

OK so I have a for loop running an equation iterating it a 0.005. I need it to print any "L" value ending in .000 and nothing else. How do I do that?

import numpy as np
import math
for D in np.arange(7, 9, 0.0050):
    N = 28
    n = 11
    A = 7.32
    P = 0.25
    C =  float(D)/float(P) #(P/8)*(2*L-N-n+((2*L-N-n)**(2)-0.810*(N-n)**(2))**(0.5)
    L = 2*C+(N+n)/2+A/C
    print("L = ", "%.3f"% float(L), '\n')

Problems I had:

I had to use np.arange as it wouldn't allow a float in a loop. If you can show me how to get around that, that'd be great.

When using np.arange, I would get "D" values like

D = 7.0009999999999994
L = 75.76939122982431 

D = 7.001499999999999
L = 75.7733725630222 

D = 7.001999999999999
L = 75.77735389888602 

D = 7.002499999999999
L = 75.78133523741519

this causes errors when I go to use these numbers later in the code

this loop takes forever to compute. If there's a better way, show me. I have to make this quick or it won't get used.

IcanCwhatUsay
  • 81
  • 1
  • 1
  • 8

2 Answers2

2

This post explained why float is not working well in python: numpy arange: how to make "precise" array of floats?

I used below code and it gave me precise decimal 3 numbers for both D & L in your calculation:

for i in range(7000, 9000, 5):
    D = i/1000

    print(D)

    N = 28
    n = 11
    A = 7.32
    P = 0.25
    C =  float(D)/float(P) #(P/8)*(2*L-N-n+((2*L-N-n)**(2)-0.810*(N-n)**(2))**(0.5)
    L = 2*C+(N+n)/2+A/C
    print("L = ", "%.3f"% float(L), '\n')
Wendy Zhu
  • 88
  • 5
0

L3 is the variable

"%.3f"% is the 3rd decimal place

% 1 == 0 I'm not sure what this does, but 0 is the number I'm looking for.

if float("%.3f"% L3) % 1 == 0: #L3 is the variable 
    do_something()
Avery
  • 2,270
  • 4
  • 33
  • 35
IcanCwhatUsay
  • 81
  • 1
  • 1
  • 8