Loop through a decimal sequence - excel

I am writing a loop in VBA for excel, and I would like to loop through a sequence of decimal numbers, rather than integers.
For example:
For i = 1 To 10
'Do something
Next i
But rather than incrementibg by 1, I would like to increment by 0.5 (or perhaps 5, or really any number other than 1).

Dim i as Single
For i = 1 To 10 Step 0.5
'
Next
But note you can get some unwanted numbers because of the floating numbers not being precise.

Sub a()
For i = 1 To 10 Step 0.1
Debug.Print i
Next i
End Sub

You can use a decimal generator.
def loop_decimal(loop_start_value, loop_stop_value, loop_step_value = 1):
# Input arguments error check
if not loop_step_value:
loop_step_value = 1
loop_start_value = decimal.Decimal(str(loop_start_value))
loop_step_value = decimal.Decimal(str(loop_step_value))
loop_stop_value = decimal.Decimal(str(loop_stop_value))
# Case: loop_step_value > 0
if loop_step_value > 0:
while loop_start_value < loop_stop_value:
yield loop_start_value
loop_start_value += loop_step_value
# Case: loop_step_value < 0
else:
while loop_start_value > loop_stop_value:
yield loop_start_value
loop_start_value += loop_step_value
Calling the generator produces:
for x in (loop_decimal(0.1, 0.9, 0.1)):
print(x)
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
To convert a float into an exact decimal value, use the str() in the decimal.Decimal() command.
decimal.Decimal(str( float_value ))
If you pass None or 0.0 to the step argument, the default value of 1 will be used.
This works for incrementing and decrementing loops.

Related

Python polynomial division - wrong remainder output

I made this polynomial division program, and it works just fine for float() values.
The script is supposed to be called using cmd like this: python main.py input.txt
The file input.txt contains two lines of numbers which the script converts to two lists of polynomial coeficients. So when the first line of input.txt is , say, 1 5 3 7, the script reads the line as 1x^0 + 5x^1 + 3x^2 + 7x^3.
When the program reads the text.txt it does the division and prints out two lines, the first being the result and the second being the remainder.
So basically if input.txt contains these lines:
0 12 -2 -4
3 -2
The program prints:
0 4 2
0
Where the first line is the result and the second one the remainder.
Now here's the code:
import sys
text = open(sys.argv[1])
dividend = list(text.readline().split())
divisor = list(text.readline().split())
for i in range(0, len(divisor)):
divisor[i] = int(divisor[i])
for i in range(0, len(dividend)):
dividend[i] = int(dividend[i])
def polynomial_division(dividend, divisor):
divid = dividend
divis = divisor[0]
for v in range(len(dividend)-(len(divisor)-1)):
divid[v] /= divis
coef = divid[v]
if coef != 0:
for i in range(1, len(divisor)):
divid[v + i] += -divisor[i] * coef
separator = -(len(divisor)-1)
output = (divid[:separator])
remainder = (divid[separator:])
print(*output, sep=' ')
print(*remainder, sep=' ')
polynomial_division(dividend, divisor)
However my teacher said the output should be int() values, so I modified it with the // operator and now the output contains int() values.
import sys
text = open(sys.argv[1])
dividend = list(text.readline().split())
divisor = list(text.readline().split())
for i in range(0, len(divisor)):
divisor[i] = int(divisor[i])
for i in range(0, len(dividend)):
dividend[i] = int(dividend[i])
def polynomial_division(dividend, divisor):
divid = dividend
divis = divisor[0]
for v in range(len(dividend)-(len(divisor)-1)):
divid[v] //= divis
coef = divid[v]
if coef != 0:
for i in range(1, len(divisor)):
divid[v + i] += -divisor[i] * coef
separator = -(len(divisor)-1)
output = (divid[:separator])
remainder = (divid[separator:])
print(*output, sep=' ')
print(*remainder, sep=' ')
polynomial_division(dividend, divisor)
But when the input.txt contains:
5 -3 6 2 -8
2 0 3 4
The output is:
2 -2
0 0 0
Which means the output is wrong as it should be:
2 -2
1 1
So my question is, what did I do wrong?

calculate average grade which accept string

In python how to get the average, which accepts as a string input parameter and returns the average of the four scores within the string as a float.
Expected output:
input output
0, 50.4, 80.3, 95.9 = 56.5
99.9, 91.3, 99.2, 98.0 = 97.1
My output right now is
input output
0, 50.4, 80.3, 95.9 = 0
99.9, 91.3, 99.2, 98.0 = 99.9
please help me to get the expected output
grade1 = 0,50.4,80.3,95.9
grade2 = 99.9,91.3,99.2,98.0
gradeArr = [grade1, grade2]
def score_average (i):
n = len (i)
total = 0
for j in i:
total = total + j
average = total
return float (average)
print("input output")
for i in gradeArr:
average = score_averages(i)
length= len(str(i))
print(str(i)[1:length -1] + " = " + str(average))
The output is 0 and 99.9 because you are returning the first number in the list in the score_average function, since the return statement is indented into the for loop, so only the first number is added to the total and then is returned. Also, if you indent it correctly, the return statement is just returning the sum of the list, so you need to return this sum divided by n to get the average. The code should look like this:
grade1 = 0,50.4,80.3,95.9
grade2 = 99.9,91.3,99.2,98.0
gradeArr = [grade1, grade2]
def score_average (i):
n = len (i)
total = 0
for j in i:
total = total + j
average = total / n # Divide the total by n
return average
print("input output")
for i in gradeArr:
average = score_average(i)
length= len(str(i))
print(str(i)[1:length -1] + " = " + str(average))

py2 vs py3 addition output difference in float format

a = 310.97
b = 233.33
sum= 0.0
for i in [a,b]:
sum += i
print(sum)
py2 o/p: 544.3
py3 o/p: 544.3000000000001
Any way to report py3 output as same as py2 with futurizing? without using round-off ?
You could convert the values to integers before performing the operation and afterwards divide by a constant e.g. 100.0 in this case.
a = 310.97
b = 233.33
c = int(a * 100)
d = int(b * 100)
sum = 0
for i in [c,d]:
sum += i
result = sum / 100.0
print(result) # 544.3
The reason for the difference is the precision in the conversion from float to string in the two versions of Python.
a = 310.97
b = 233.33
sum = 0.0
for i in [a,b]:
sum += i
print("{:.12g}".format(x)) # 544.3
See this answer for further details: Python format default rounding when formatting float number

How to contain a loop or multiply the loop till a precision is met?

I am currently working on a problem with Wallis algorithm for approximating pi. The problem requires that I call the function Wallis(precision) to return a value of the Wallis pi, and count the number of steps to reach the precision.
The precision is basically pi minus wallis_pi
i have tried while loops which would allow me to enter the precision, but i am unable to get the loop to stop at the required number.
def wallis(x):
counter = 0
my_pi = 2.0
pi
j= 1.0
while x > abs(pi-my_pi):
top = (4*(j**2))
btm = (4*(j**2)-1)
my_pi *= top/btm
j += 1
my_pi = 2 * my_pi
counter += 1
print(my_pi)
return my_pi, counter
If x is your precision.
The condition should be -
while error > precision:
You have written
while precision > error:
That is not correct.
Try this and just make the precison half of what you actually need to prevent that multiplication by 2 which is what causing the infinite loop.
import math
pi = math.pi/2.0
def wallis(x):
counter = 0
my_pi = 1.0
j = 1.0
while abs(pi-my_pi) > x:
prod = (4.0*(j**2))/(4.0*(j**2) - 1)
my_pi *= prod
j += 1.0
counter += 1
return my_pi, counter
def wallis(x):
x = x/2 ## precision is also halved as the pi value and m_pi values are divided by 2 of when pi-m_pi>x
counter = 0 ## counter after each term has been multiplies within the equation
my_pi = 1.0 ## wallis pi thats calculated
hlfpi = pi / 2 ## half of pi used for comparison due to equation
j = 1.0 ## the value for j that increases by 1 each time
while abs(hlfpi - my_pi) > x:
top = (4 * (j ** 2))
btm = (4 * (j ** 2) - 1)
prod = float(top) / float(btm)
my_pi *= prod
j += 1.0
counter += 1
my_pi *= 2
return my_pi, counter
print(wallis(x))

cosine function by Maclaurin series using for loop and stops when difference in error is already by what i desired

Can you help me code a cosine function by Maclaurin series. I want to eliminate inputting number of iterations. I just want it to keep going until i achieve my desired accuracy (in my code 0.000000000000001). Kindly answer simply coz im a real beginner in python.
from math import *
variable_x = float(input("Input for cosine function: "))
number = int(input("Input number of iterations: "))
cosine_x = 0
for number in range (0,number):
old = cosine_x + (pow(-1, number)*pow(variable_x,2*number)/factorial(2*number))
print(old)
if 0 < abs(old - cosine_x) < 0.000000000000001:
break
cosine_x = old
print(number)
Result:
Input for cosine function: 5
Input number of iterations: 100
1.0
-11.5
14.541666666666668
-7.159722222222221
2.528397817460318
-0.16274663800705413
0.34693981189206935
0.276927936905926
0.28422084055031593
0.283625015089173
0.28366421413266923
0.2836620929723069
0.28366218903935225
0.2836621853444659
0.2836621854666513
0.2836621854631402
0.2836621854632287
0.2836621854632267
0.28366218546322675
18
To avoid input the number of iterations, you just use while loop:
from math import *
variable_x = float(input("Input for cosine function: "))
cosine_x = 0
number = 0
while True:
old = cosine_x + (pow(-1, number)*pow(variable_x,2*number)/factorial(2*number))
print(old)
if 0 < abs(old - cosine_x) < 0.000000000000001:
break
cosine_x = old
number += 1
print(number)

Resources