Square Root algorithm bug - python

I have tried to compute this algorithm with python and it doesn't seem to work:
lt = False
x = 5
g = 2
while lt == False:
if g*g > (x-0.1) and g*g < (5.1):
lt = True
print(g+"IS THE SQUARE ROOT")
else:
g = (g + x/g)/2
print(g)
In the else loop, I printed g to see the outcome of my algorithm in each loop because I was experiencing slow computation previously and wanted to see what the problem was, and now print(g) seems to consistently be returning 2. I'm new to python and the problem is probably staring me in the face but I can't seem to figure it, any help would be much appreciated!

x = float(5)
g = float(2)
Python rounds int in v2.x. Hope this helps.

You are getting 2 because python is rounding the numbers because you are using integers, you need to use floats like so:
x = float(5)
g = float(2)
Now:
>>g = (g + x/g)/2
>>print(g)
2.25

Swap the else: clause and block and the print() call.

The problem is your mix of tabs and spaces. Python expects you to be consistent, and it is preferred to use four spaces for indents. Tabs are a different character altogether, and do not always appear the same width. In some environments they are 4 characters wide. Python interprets them as 8 characters wide.
These two lines are using spaces:
if g*g > (x-0.1) and g*g < (5.1):
lt = True
All other lines are using tabs.

The problem is that python rounds integers. You need to enter set x and g as floats instead
x = float(5)
g = float(2)
This should work, good luck! :)
This works in python 2.x but I don't know what version you are using so this is the best answer I can provide.

Related

Slicing string made up of digits sometimes returns variable lengths

I'm working my way through Project Euler using python and I'm currently working on problem 8. I've encountered a problem with the first way I tried solving the problem. My initial solving method is below
num = '''7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'''
#print(stringNumber)
seriesLen = 13
firstIndex = 0
lastIndex = seriesLen
topValue = 0
topSeries = ''
while lastIndex < len(num):
lastIndex = firstIndex + seriesLen
number = int(num[firstIndex:lastIndex])
print(firstIndex, lastIndex)
lastIndex = firstIndex + seriesLen
if len(str(number)) != lastIndex - firstIndex:
print(lastIndex - firstIndex)
print(len(str(number)))
firstIndex += 1
# print(number)
What this code is supposed to do is go through the entire 1000 digit number given in the problem 13 digits at a time and print those 13 digits. But, for some reason it doesn't always print 13 digits and I cannot figure out why. Sometimes it takes as few as 10 digits instead of 13. I've tried this with several different strings too and it does the same thing. I've talked to my Prof about this and she is quite certain the slicing is correct so I figured I'd post this issue here.
For those who know the problem I'm talking about here I am aware that this doesn't give me the answer to the problem - it's just a MWE to demonstrate my issue.
This happens because you convert the sliced digits to an int here:
number = int(num[firstIndex:lastIndex])
This removes any leading zeros from the string, which is why you get variable lengths sometimes. Just remove this, and your code should work as expected.
number = num[firstIndex:lastIndex]

How do I put this equation into python?

I need to put this equation
P*(1 + r/100n)^nt
into python. Can anyone help me?
I've tried this, but it won't get me right answer
p*(1+r/100*n)**(n*t)
p is 116000
t is 35
r is 4
n is 12
I'm suppose to get $469,309.30 from above values, but the number I get is way too high. Its only been hours since I started to learn programming. I just have no idea what to do.
It might be an order of operations issue where Python is dividing r by 100 first. I would try the following:
p*(1+r/(100*n))**(n*t)
Just follow the PEMDAS rule and you'll be fine man :D.
p = 116000
t = 35
r = 4
n = 12
answer = p*(1+r/(100*n))**(n*t)
print(answer)
out: 469309.29562481085
Try this,
>>> "${:,.2f}".format(p*(1+r/(100*n))**(n*t))
'$469,309.30'
Explanation:
PEMDAS - Rule
Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction
You need to follow this rule, while writing math equations in code.
In your case, r was divided by 100 as / comes first then it was multiplied by n.
According to bodmas it will divide r by 100 so you need to use brackets at r/(100*n)
result=p*(1+r/(100*n))**(n*t)
print(result)
output:
469309.29562

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.

Python: split a float into different variables, add last float to first int and calculate

This is just for learning purpose. I want to do the following.
x = 5.0
y = 888.0
z= y / x
print z # 177.6
...?
Now I want to change the last part of the float to int and add the last number of the float (.6) as 6 to the first number (to get 777 from 177.6). After that I want to add the difference of 777 and y to a new variable to get 888 back.
Would be great if someone can explain how to do that! :)
edit: possible solution in the last code of this post.
The purpose of this is to understand how to perform such tasks in python and to get a better understanding of something I would call "mathematic symmetry".
You can find this symmetry while performing calculations like:
666 / 5.0 #133.2
777 / 5.0 #155.4
888 / 5.0 #177.6
999 / 5.0 #199.8
666.6 / 5.0 #133.32
I'm not an academic, so maybe this sounds mad. It is just a part of a theory in my spaghetti monster mind and with a script I could further investigate what this is about. ;)
With the help of the comments i was able to create this code. I'm quite sure it looks ugly from a professional programmers view, but hey, it's one of my first steps and im very happy with that! Thank you again! :)
x = 5.0
y = 888.0
z= y / x
print z # 177.6
print
a = int(str(z)[0])
print "First Number = " + str(a)
print
b = int(str(z)[1])
c = int(str(z)[2])
print "In between = " + str(b) + str(c)
d = int(str(z)[-1]) # treat z as string, take first string after . from z and format it back to int
print "Last Number = " + str(d)
print
res = str(a+d) +str(b) +str(c)
to_int = int(res)
dif = y - to_int
add = to_int + dif
print add
Edit: Is there some magic happening in this code? The actual code seems to be inteded to calculate numbers like 777.7 But when i run it with y = 7277.7727 it gives the correct output even if i only have 2 digits in between? I was expecting wrong calculations. o0
Edit: Resolved. A logical failure in the calculations created the unexpected result. Practically i was printing y at the end. xD
I think the safest way is using string manipulation:
int(str(177.123)[-1])
3
int(str(177.123).split('.')[-1])
123
But I am afraid you'll be eventually bitten by floating point precision issues. A package for symbolic math like sympy might be more suitable for your purpose than standard floating point arithmetic.

NameError: name 'z' is not defined

I am trying to make a binary to decimal coverter for a project in my computing class and I get this error with my code: "NameError: name 'z' is not defined" I've looked up answers and they fix one error but give another. Here is the code:
bd = input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""")
if bd == 'a':
answer = input("""
Please enter a Binary number. Up to, and including, 8 digits of 1 and 0
""")
z += 2
for i in range(8):
if answer [ i ] == '1':
answer += 1*z**i
Any help would very much be appreciated!
Is this your first programming language? If so, let me introduce you to the concept of Variable Initialization.
When a computer is running code, it is processing bytes between the memory and the CPU. You probably know this already, but what you may not realize is that in your code, you are asking the computer to perform an operation on z, a variable that does not exist yet.
Keep something else in mind. Python does not need to initialize a variable in order to assign to it. So, why do you need to initialize z then before the program will run? The answer is simple: your first reference to z is an operation. Even though Python can automatically (without initialization) assign variables on the fly (different from other programming languages, usually), it still needs said variable to exist before math can be done with it.
The simple solution is to add z = 0 at any point before if bd == 'a': (because if you put it after, every time it goes into the if statement, it will over-write z with 0, ruining the logic for it.
Happy coding!
EDIT: In addition to this issue, the problem you will face with the error:
File "C:/Users/<USERNAME>/Desktop/Task 1.py", line 15, in <module> answer += 1*z**i TypeError: Can't convert 'int' object to str implicitly
Comes from the line:
if answer [ i ] == '1':
You see, when you type '1', you are saying that 1 is a string because you surround it with quotes, just the same as if you had written:
if answer [i] == "1":
What you need, instead, is the line
if answer [i] == 1:
Because that tells it to assign the number 1. Then, in the operation
answer += 1*z**i
You will be telling it to multiply three numbers instead of two numbers and the string "1".
In other languages like C, you must declare variables so that the computer knows the variable type. You would have to write string variable_name = "string text" in order to tell the computer that the variable is a string. In Python, the type casting happens automatically. Python sees variable = "string text" and it knows that because you used "", it is a string-type variable. Unfortunately, this means that you mistakenly made 1 a string.
Understand?
EDIT 2: The Happening
Okay, so you kept running into errors. And when I ran your code, I kept running into different errors. Because the of the tricky syntax and changing in types implicitly, I decided a much easier route to go was to rewrite the code and explain to you how and why it works. So, here is the new code:
bd = raw_input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""").lower()
## ORIGINAL CODE
##
##if bd == 'a':
## answer = input("""
##Please enter a Binary number. Up to, and including, 8 digits of 1 and/or 0
##""")
##
## print answer
## for i in range(8):
## z += 2
## if answer[i] == '1':
## answer += 1*z**i
##NEW CODE
if bd == 'a':
number_original = raw_input("Please enter a Binary number (a string of 1's and 0's)")
j = 0
number_converted = 0
for i in reversed(number):
if i == '1':
number_converted += 2**j
j+=1
print number_converted
From top to bottom, I'll go over what I wrote (I'll skip over your code) and I'll explain what it does and how it does it. Hopefully, this will help you in the decimal->binary conversion, as I assume you still have that to do.
So we begin with a few changes to your opening question. Where before you had bd=input(""), you now have bd=raw_input("").lower().
bd will still be a or b. But there was some shaky type handling in that statement, at least on my end. So, I made use of raw_input() which turns your answer into a string regardless of what it is. If you answer with 101010011 for instance, it will store the variable "101010011" and not the number 101010011 (though this would be wrong anyway-- it would be base 10, so it would actually be 101,010,011)... I also added .lower(), which as you may guess, turns your answer from whAtevErYouWritE to whateveryouwrite. This is an example of data sanitation and is vital in a good program, because people can be stupid and expect a computer to know what they mean. Computers, of course, have no idea what you mean, so you have to be very careful, know what mistakes a user can make, and plan ahead for it (BONUS: Here's a comic on the subject, which you will now definitely get).
So onto the meat of the program. We start by testing the condition for answer a with:
if bd == 'a':
Now, if you put in A, this would still work because of .lower(). If you put b, if wouldn't work (you have yet to put in your decimal->binary code!), and always remember that some day, someone will put in C, just to troll you, so include an elif for b and an else for anything else.
After this we encounter the first signs of it just being my code.
number_original = raw_input("Please enter a bin...
I've named it number_original because in code, it's always best practice to be clear and concise. Remember, the variable name this_is_the_variable_i_use_to_calculate_my_circumference is better than x so long as it explains clearly what it is, and helps other people understand your work. More advanced coders like to be ambiguous in this case, but a lot of the time it's just showing off.
I used raw_input() again because I actually want my number to be stored as a string. Remember when I said that 101010011 would be 101,010,011 to the computer? This would be very difficult to check, because the computer will assume a base 10 number. Thus, I just had it stored as a string, "101010011", and avoided that whole issue. There is also the added bonus to this that strings have manipulating methods that make it easier to work with, easier than the logic you were trying to introduce with range(8). That manipulator can be seen shortly.
Next, we declare our variables:
j = 0 #This 'j' accomplishes the same work done by your 'z' variable.
number_converted = 0 #this will be correctly converted by the end, as we add to it.
As mentioned in my original version of this post, these are initialized because the first time you operate on them inside the loop, you do math to them, and they need to exist as a number before you can do that. Even if they start at 0.
So now we look at the most interesting part, the for loop. Based on your original work, you kind of get how for loops work, but I'll go over them in a lot of detail so that hopefully, it helps you as much as possible when you need to see the big picture.
In a for loop, you are meant to iterate over a range of numbers. In your original code, you generated the range [0,1,2,3,4,5,6,7] to iterate over. I think you did this so you could keep track of which position in the binary number you were at, and I'm doing that as well, but in a different way, and one that I devised slowly in order to help you make the best decimal-to-binary system I could.
First, remember that number is a string now, so `"101010011". Next, realize that strings have indexes that can be accessed like so.
demo_string = "super mario brothers"
print demo_string[0]
print demo_string[1]
print demo_string[2]
print demo_string[3]
print demo_string[4:10]
print demo_string[:10] #if you leave out the first number, it starts at the beginning
print demo_string[10:] #if you leave out the last number, it ends at the end.
The above code will give you the following result:
s
u
p
e
r mari
super mari
o brothers
Take special notice that an index starts at 0, which is why demo_string[1] is u and not s.
Knowing this, you may begin to realize why we left number_original as a string: now we can use its index and iterate over that instead of making our own range with range()! This is why we can type for i in reverse(number_original); because that makes it loop from reverse(number_original)[0] to reverse(number_original)[i], as far as i is able to go. **Note:***We will go over why we are using* reverse() shortly.
It's time for number/computer science and math!
Have you learned yet about expressing every binary digit in the form of a power of two? I know you understand the concept underlying conversion in a binary number. Well, here's another cool trick you may or may not be aware of:
... # # # # # # <--The binary number, eg "101010"
...32 16 8 4 2 1 <--What each digit stands for in decimal form
... 5 4 3 2 1 0 <--The power of two that it stands for (2^5=32, 2^4=16...)
Another thing you'll realize is that typically (not always, but usually, binary numbers are read from right to left. This will come in handy in a moment).
So we're at the for loop. We know now that we can iterate through a string. But binary digits are read right-to-left. So, the binary number 10 = 2, not 10 = 1. This is why we wrote:
for i in reversed(string):
Because now, the for loop will iterate backwards! It will read the string right-to-left for us.
We also know that 2^x = (digit value in decimal).
So what we'll do in each iteration of the for loop is:
Check if i == '1' Note, this time we want it to be a string.
If i == '1', as in, the digit we're highlighting is a '1', then...
Take number_converted and add number_converted + 2^j
Then accumulate once to j, so it's one higher for the next trip.
To put this visually, I'll do two loops on the number 101010011.
Loop 4
j = 4
number_converted = 3 (still being converted)
is reversed(number_original)[3] == '1'? ( 1 1 0 0 1 0 1 0 1, so no)
then add 1 to j (j = 5)
Loop 5
j = 5
number_converted = 3 (still being converted)
is reversed(number_original)[4] == '1'? (1 1 0 0 1 0 1 0 1, so yes!)
then take number_converted (3) and add 2^j (2^5 = 16) to it (number_converted = 25)
then add 1 to j (j = 6)
Loop 6
j = 6
number_converted = 35 (still being converted)
this will continue until end!
So there you have it. Binary to decimal, in python.
If you have any questions about this, please ask. I remember being confused about this stuff when I first started!
And again, Happy Coding.
You need to assign z to a value becore you can use +=
Add z = 0 to the top of your script.
You never initialized z, so if you put z = 0 on the line above the if statement, you'll no longer have the issue
bd = input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""")
z = 0
if bd == 'a':
answer = input("""
Please enter a Binary number. Up to, and including, 8 digits of 1 and 0
""")
z += 2
for i in range(8):
if answer [ i ] == '1':
answer += 1*z**i
You never defined z.Try this code:
z = 0
bd = raw_input("Would you like to convert a number into:\n a) Binary to Decimal\n b) Decimal to Binary")
if bd == 'a':
answer = raw_input("Please enter a Binary number. Up to, and including, 8 digits of 1 and 0")
z += 2
ex = 0
for i in xrange(8):
if answer[i] == '1':
ex += 1*z**i

Categories

Resources