How to make python print 1 as opposed to 1.0 - python

I am making a math solving program, it keeps printing the whole numbers as decimals. Like 1 is 1.0, 5 is 5.0, and my code is:
print("Type in the cooridinates of the two points.")
print("")
print("---------------------")
print("First point:")
x1 = int(input("X: "))
y1 = int(input("Y: "))
print("")
print("---------------------")
print("Second point:")
x2 = int(input("X: "))
y2 = int(input("Y: "))
m = (y1-y2) / (x1-x2)
b = y1 - m * x1
round(m, 0)
round(b, 0)
print("Completed equation:")
print("")
if b < 0:
print("Y = "+ str(m) +"X - "+ str(b) +".")
elif b > 0:
print("Y = "+ str(m) +"X + "+ str(b) +".")
elif b == 0:
print("Y = "+ str(m) +"X.")
input("Press enter to continue.")

Since you're dividing integers, Python represents the result as a float, not as an int. To format the floats as you'd like, you'll have to use string formatting:
>>> print('{:g}'.format(3.14))
3.14
>>> print('{:g}'.format(3.0))
3
So plugging it into your code:
print("Y = {:g}X - {}.".format(m, b))

Try this,
> x = 10.0
> print int(x)
10
> print x
> 10.0
Is this what you are really looking for?

When you do this:
m = (y1-y2) / (x1-x2)
You get a float (a floating point representation of a real number), not an int (an integer).
Then, because m is a float, b too is a float. Then, when you call str on a float, you get a decimal point.
The right way to fix this depends on what you actually want to do.
If you really want to deal only with integers, you can use integer division:
m = (y1-y2) // (x1-x2)
That means if, say, x1, x2, y1, y2 = 4, 2, 2, 1 you'll end up with b = 2 (2 - 0 * 4). I suspect that isn't what you want; you actually want to multiply that 4 by 1/2, and then round the result afterward.
In that case, you can do the conversion the same place you round:
m = int(round(m, 0))
b = int(round(b, 0))
Note that your existing calls to round didn't actually do anything; round(m, 0) doesn't modify m, it returns a new value that's the rounded version of m, which you have to assign back to m (or somewhere else).
One more thing to consider: You probably really do want literally one half, not "the closest floating point representation to 0.5".
You probably don't actually care about the difference—unless you're using quite large integers, the rounding errors won't ever be visible. But if you do care, you may want to consider using a third-party exact-fraction module (e.g., clnum), or possibly the standard library decimal. This would mean you have to be more explicit, so I wouldn't do this unless you expect it to be necessary. But if it is necessary, it would look something like this:
m = decimal.Decimal(y1-y2) / (x1-x2)
b = y1 - m * x1
m = int(m.to_integral(rounding=decimal.ROUND_HALF_UP))
b = int(b.to_integral(rounding=decimal.ROUND_HALF_UP))
Finally, you can always keep the numbers around as floats (or Decimals, etc.), never rounding or converting them, and force them to print as integers anyway:
print("Y = {:.0g}X - {:.0g}.".format(m, b))

Just tried this one
n = -0.0
#n = 0.0
#n = +0.0
#n = 5.0
#n = 5
#n = 5.4
#n = -5.0
#n = -5
#n = 5.25
n = (n**2)**0.5
n = '{:g}'.format(n)
if n.find('.') == -1:
n=int(n)
else:
n=float(n)
print(n)
print(type(n))
-------------------------------------------------------------------
The same in one line
n = -0.0
n = int('{:g}'.format((n**2)**0.5)) if
'{:g}'.format((n**2)**0.5).find('.') == -1 else
float('{:g}'.format((n**2)**0.5))
-------------------------------------------------------------------
Example for a list
numlist = [-0.0, 0.0, +0.0, 5.0, 5, 5.4, +5.0, +5, +5.15,-5.0, -5, 5.25]
print(f'Numbers are {numlist}')
for n in numlist:
print(f'Before n is {n} and type of n is {type(n)}')
n = int('{:g}'.format((n**2)**0.5)) if '{:g}'.format((n**2)**0.5).find('.')
== -1 else float('{:g}'.format((n**2)**0.5))
print(f'After n is {n} and type of n is {type(n)}')

Related

Python removing first 3 digits in a number

Hopefully a simple one, I have a number, say 1234567.890 this number could be anything but will be this length.
How do I truncate the first 3 numbers so it turns into 4567.890?
This could be any number so subtracting 123000 will not work.
I'm working with map data in UTM coordinates (but that should not matter)
Example
x = 580992.528
y = 4275267.719
For x, I want 992.528
For y, I want 267.719
Note: y has an extra digit to the left of the decimal so 4 need removing
You can use slices for this:
x = 1234567.890
# This is still a float
x = float(str(x)[3:])
print(x)
Outputs:
4567.89
As [3:] gets the starts the index at 3 and continues to the end of the string
Update after your edit
The simplest way is to use Decimal:
from decimal import Decimal
def fmod(v, m=1000, /):
return float(Decimal(str(v)) % m)
print(fmod(x))
print(fmod(y))
Output
992.528
267.719
If you don't use string, you will have some problems with floating point in Python.
Demo:
n = 1234567.890
i = 0
while True:
m = int(n // 10**i)
if m < 1000:
break
i += 1
r = n % 10**i
Output:
>>> r
4567.889999999898
>>> round(r, 3)
4567.89
Same with Decimal from decimal module:
from decimal import Decimal
n = 1234567.890
n = Decimal(str(n))
i = 0
while True:
m = int(n // 10**i)
if m < 1000:
break
i += 1
r = n % 10**i
Output:
>>> r
Decimal('4567.89')
>>> float(r)
4567.89
This approach simply implements your idea.
int_len is the length of the integer part that we keep
sub is the rounded value that we will subtract the original float by
Code
Here is the code that implements your idea.
import math
def trim(n, digits):
int_len = len(str(int(n))) - digits # length of 4567
sub = math.floor(n / 10 **int_len) * 10**int_len
print(n - sub)
But as Kelly Bundy has pointed out, you can use modulo operation to avoid the complicated process of finding the subtrahend.
def trim(n, digits):
int_len = len(str(int(n))) - digits # length of 4567
print(n % 10**int_len)
Output
The floating point thing is a bit cursed and you may want to take Corralien's answer as an alternative.
>>> n = 1234567.890
>>> trim(n, 3)
4567.889999999898
def get_slice(number, split_n):
return number - (number // 10**split_n) * 10**split_n

SQRT using any method (f.e. Newton) but with fixed number of digits after separator

I need to calculate in Python 3 square root of number num (0 < num <= 1000000000000000 ) using any method, any mathematic algorithm. The problem is I need to calculate it to P (0 <= P <= 10000) digits after dot (floating number separator) and the result should be rounded down (always to smaller number). Of course, I cannot use math.sqrt().
So if num is 55 and P = 6, function should return:
7,416198
So if num is 55 and P = 10, function should return:
7,4161984870
Here is my code:
def square_root(num, P):
x = num
y = 1
e = 10 ** (-P)
while (x - y > e):
x = (x + y) / 2
y = num / x
return x
Should I use Decimal type?
For the most part, the algorithm you already have is correct. The main issue is precision, which, as you guessed, you can do with the Decimal class.
import Decimal
def square_root(num, P):
# need to set the decimal precision to more than enough digits to handle the full calculation
# (the number of decimal places, plus the number of digits in the original number,
# should be enough - this counts the numbers both before and after the decimal point)
# I add +2 to give some room to spare, as well
decimal.getcontext().prec = P + len(str(num)) + 2
# now, do the algorithm you have, except with everything as fixed-point Decimal objects
x = decimal.Decimal(num)
y = decimal.Decimal(1)
e = decimal.Decimal(10) ** decimal.Decimal(-P)
# important: I changed this to >= so that it runs when P=0.
# Otherwise we output 2 when P=0, when we should output 1.
while (x - y >= e):
x = (x + y) / 2
y = num / x
# now, truncate to exactly the desired number of digits
# this is straightforward - we can just use the built-in `round()` method with P
# we subtract e/2 to simulate always rounding down, since round() simply rounds to closest.
return round(x - (e / 2), P)
This works for an arbitrarily high precision:
>>> square_root(2, 0)
Decimal('1')
>>> square_root(2, 1)
Decimal('1.4')
>>> square_root(2, 3)
Decimal('1.414')
>>> square_root(2, 5)
Decimal('1.41421')
>>> square_root(2, 100)
Decimal('1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727')
>>> square_root(2, 10000)
Decimal('1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372352885092648612494977154218334204285686060146824720771435854874155657069677653720226485447015858801620758474922657226002085584466521458398893944370926591800311388246468157082630100594858704003186480342194897278290641045072636881313739855256117322040245091227700226941127573627280495738108967504018369868368450725799364729060762996941380475654823728997180326802474420629269124859052181004459842150591120249441341728531478105803603371077309182869314710171111683916581726889419758716582152128229518488472089694633862891562882765952635140542267653239694617511291602408715510135150455381287560052631468017127402653969470240300517495318862925631385188163478001569369176881852378684052287837629389214300655869568685964595155501644724509836896036887323114389415576651040883914292338113206052433629485317049915771756228549741438999188021762430965206564211827316726257539594717255934637238632261482742622208671155839599926521176252698917540988159348640083457085181472231814204070426509056532333398436457865796796519267292399875366617215982578860263363617827495994219403777753681426217738799194551397231274066898329989895386728822856378697749662519966583525776198939322845344735694794962952168891485492538904755828834526096524096542889394538646625744927556381964410316979833061852019379384940057156333720548068540575867999670121372239475821426306585132217408832382947287617393647467837431960001592188807347857617252211867490424977366929207311096369721608933708661156734585334833295254675851644710757848602463600834449114818587655554286455123314219926311332517970608436559704352856410087918500760361009159465670676883605571740076756905096136719401324935605240185999105062108163597726431380605467010293569971042425105781749531057255934984451126922780344913506637568747760283162829605532422426957534529028838768446429173282770888318087025339852338122749990812371892540726475367850304821591801886167108972869229201197599880703818543332536460211082299279293072871780799888099176741774108983060800326311816427988231171543638696617029999341616148786860180455055539869131151860103863753250045581860448040750241195184305674533683613674597374423988553285179308960373898915173195874134428817842125021916951875593444387396189314549999906107587049090260883517636224749757858858368037457931157339802099986622186949922595913276423619410592100328026149874566599688874067956167391859572888642473463585886864496822386006983352642799056283165613913942557649062065186021647263033362975075697870606606856498160092718709292153132368281356988937097416504474590960537472796524477094099241238710614470543986743647338477454819100872886222149589529591187892149179833981083788278153065562315810360648675873036014502273208829351341387227684176678436905294286984908384557445794095986260742499549168028530773989382960362133539875320509199893607513906444495768456993471276364507163279154701597733548638939423257277540038260274785674172580951416307159597849818009443560379390985590168272154034581581521004936662953448827107292396602321638238266612626830502572781169451035379371568823365932297823192986064679789864092085609558142614363631004615594332550474493975933999125419532300932175304476533964706627611661753518754646209676345587386164880198848497479264045065444896910040794211816925796857563784881498986416854994916357614484047021033989215342377037233353115645944389703653166721949049351882905806307401346862641672470110653463493916407146285567980177933814424045269137066609777638784866238003392324370474115331872531906019165996455381157888413808433232105337674618121780142960928324113627525408873729051294073394794330619439569367020794295158782283493219316664111301549594698378977674344435393377099571349884078908508158923660700886581054709497904657229888808924612828160131337010290802909997456478495815456146487155163905024198579061310934587833062002622073724716766854554999049940857108099257599288932366154382719550057816251330381531465779079268685008069844284791524242754410268057563215653220618857512251130639370253629271619682512591920252160587011895967322442392674237344907646467273753479645988191498079317180024238554538860383683108007791824664627541174442500187277795181643834514634612990207633430179685543856316677235183893366670422221109391449302879638128398893117313084300421255501854985065294556377660314612559091046113847682823595924772286290426427361632645854433928772638603431498048963973633297548859256811492968361267258985738332164366634870234773026101061305072986115341299488087744731112295426527516536659117301423606265258690771982170370981046443604772267392829874152593069562063847108274082184906737233058743029709242899481739244078693752844010443990485208788519141935415129006817351703069386970590047425157655248078447362144105016200845444122255956202984725940352801906798068098300396453985685930458625260637797453559927747299064888745451242496076378010863900191058092874764720751109238605950195432281602088796215162338521612875228518025292876183257037172857406763944909825464422184654308806610580201584728406712630254593798906508168571371656685941300533197036596403376674146104956376510308366134893109478026812935573318905519705201845150399690986631525124116111925940552808564989319589834562331983683494880806171562439112866312797848371978953369015277600549805516635019785557110140555297633841275044686046476631832661165182067501204766991098721910444744032689436415959427921994423553718704299559240314091712848158543866005385713583639816309452407557009325168243441682408361979273372825215462246961533217026829950979089034594858878349439616204358422497397187113958927305092197054917176961600445580899427878880369169432894595147226722926124850696173163809410821860045286102696547576304310256027152313969482135519821409716549097319992834925674097490392297126348693414574933198041718076111963902278664075922434167762466236238913110270343304576368141128321326308582239456219598086612939996201234156176318174312420089014983848560480879864608393596492366514296812577314322914568716827621996118278269531574983802624651759054103976181287604216386134502213262727756612441133610775195557749508656360673786650623185640699122801875741785494661253275997697960597760590756489106661015838417202818530432119044657752554277543798726054881736198267581686283295260789932226683602838513512281059318591028641508157056319717315183136250243590414632122392176633982689368253150530059891547029095371932662073411234947433678846902013904978428521634144292145895582878476693946464267812219049785636355263368278051860098699248937786002398769169807656621943898544370805946433362333810587458162354756001365924352426571430834655457680023708146757325254702550747637471635067851599173693793251032682760628645914618204721486370370771926926823623334720379245964691810526139153086280291440965482563873092730426544662929045896063751918711469345361973324789572707031530930901921199199993615765003503984054067425387927527922724733566770607837911384488936261367657060263600315132952095395202854897384486256134924414708607086602676349978793420875836121947116994223848482595914304528107062601508969135303017720062717054402090669514915274597719705947695474095210287872557856880022193717743558110793930883384558648277291008629554566141306721230848740227121058686323388237413884428938155444647105755651468435702946635062893873569868688376480326519528414653517395302736120137420300986739838514321900436028982698293529399414129230580384565022707216815161941011449826301364900877048398488386090653368599054583895203185648041493272142390865164999431659207965953569430723112911629286797517156688905439322035691293324570208067194440497304943981408227829602799424541083166675921424835182723817205041039274288801556223380796147512433514731021284545944899444996000752437519570116683417447490795882099517836768023236517674972301487457742725994760962198432714835298611190272873584905217975908374197486026706053746231530039375212367867752848692195857137554269684827836317861109933680143915905974842858054516130230143979057016108898627779610750673332676048654929251399781390535882276893732204941483940135560356560442140176120605131806891989962606184831853401836237821726637580455247196266174925422852804571442048578342113228008528704205488992341278554812367615377071042544698685219911228354266349997127483660762462418207364666171283947484732804744304033441072004287271275670279567582429262719454580530026664899650795697781786219421720052371653694677041951119127046248360511302890464377511486948878496151188414719100012558838366606772084112351535588112677895715585904125762616010675131535802124273318710006358249545040995794072547989003168265123731190556682915194305370848930786919742829049038603723116099283424317122250994547150192866648787107951995180054633883844315481724635480244518030845273431000621371034625733060012349737443558180965678464641533905146569193245623531405779193698988423647183525375805257713311200797104068315492665402026046806818391437827214769063242469517128636738443139833371176159418699934662623453734523567940124168092291163609563721674528391709909146648507392051516056047378710615470216996074656930979442612146925615934256494019122989514732544715181263258368897282262833295240359700727863364604594707124174729468775705958157349962848099567839255474240448991887071069675242507745201229360810574142653234724064162141033353340551104521261750359028403745459186450472762434207177092979354010214096464502836834180407586081001407216192477179809859681115404464437285689592868319777977869346415984697451339177415379048778808300220583350467465553230285873258352')
Of course, you can also take str() of the return value to convert it into a string.

Karatsuba Multiplication Implementation

I recently implemented Karatsuba Multiplication as a personal exercise. I wrote my implementation in Python following the pseudocode provided on wikipedia:
procedure karatsuba(num1, num2)
if (num1 < 10) or (num2 < 10)
return num1*num2
/* calculates the size of the numbers */
m = max(size_base10(num1), size_base10(num2))
m2 = m/2
/* split the digit sequences about the middle */
high1, low1 = split_at(num1, m2)
high2, low2 = split_at(num2, m2)
/* 3 calls made to numbers approximately half the size */
z0 = karatsuba(low1, low2)
z1 = karatsuba((low1+high1), (low2+high2))
z2 = karatsuba(high1, high2)
return (z2*10^(2*m2)) + ((z1-z2-z0)*10^(m2)) + (z0)
Here is my python implementation:
def karat(x,y):
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
m = max(len(str(x)),len(str(y)))
m2 = m / 2
a = x / 10**(m2)
b = x % 10**(m2)
c = y / 10**(m2)
d = y % 10**(m2)
z0 = karat(b,d)
z1 = karat((a+b),(c+d))
z2 = karat(a,c)
return (z2 * 10**(2*m2)) + ((z1 - z2 - z0) * 10**(m2)) + (z0)
My question is about final merge of z0, z1, and z2.
z2 is shifted m digits over (where m is the length of the largest of two multiplied numbers).
Instead of simply multiplying by 10^(m), the algorithm uses *10^(2*m2)* where m2 is m/2.
I tried replacing 2*m2 with m and got incorrect results. I think this has to do with how the numbers are split but I'm not really sure what's going on.
Depending on your Python version you must or should replace / with the explicit floor division operator // which is the appropriate here; it rounds down ensuring that your exponents remain entire numbers.
This is essential for example when splitting your operands in high digits (by floor dividing by 10^m2) and low digits (by taking the residual modulo 10^m2) this would not work with a fractional m2.
It also explains why 2 * (x // 2) does not necessarily equal x but rather x-1 if x is odd.
In the last line of the algorithm 2 m2 is correct because what you are doing is giving a and c their zeros back.
If you are on an older Python version your code may still work because / used to be interpreted as floor division when applied to integers.
def karat(x,y):
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
m = max(len(str(x)),len(str(y)))
m2 = m // 2
a = x // 10**(m2)
b = x % 10**(m2)
c = y // 10**(m2)
d = y % 10**(m2)
z0 = karat(b,d)
z1 = karat((a+b),(c+d))
z2 = karat(a,c)
return (z2 * 10**(2*m2)) + ((z1 - z2 - z0) * 10**(m2)) + (z0)
i have implemented the same idea but i have restricted to the 2 digit multiplication as the base case because i can reduce float multiplication in function
import math
def multiply(x,y):
sx= str(x)
sy= str(y)
nx= len(sx)
ny= len(sy)
if ny<=2 or nx<=2:
r = int(x)*int(y)
return r
n = nx
if nx>ny:
sy = sy.rjust(nx,"0")
n=nx
elif ny>nx:
sx = sx.rjust(ny,"0")
n=ny
m = n%2
offset = 0
if m != 0:
n+=1
offset = 1
floor = int(math.floor(n/2)) - offset
a = sx[0:floor]
b = sx[floor:n]
c = sy[0:floor]
d = sy[floor:n]
print(a,b,c,d)
ac = multiply(a,c)
bd = multiply(b,d)
ad_bc = multiply((int(a)+int(b)),(int(c)+int(d)))-ac-bd
r = ((10**n)*ac)+((10**(n/2))*ad_bc)+bd
return r
print(multiply(4,5))
print(multiply(4,58779))
print(int(multiply(4872139874092183,5977098709879)))
print(int(4872139874092183*5977098709879))
print(int(multiply(4872349085723098457,597340985723098475)))
print(int(4872349085723098457*597340985723098475))
print(int(multiply(4908347590823749,97098709870985)))
print(int(4908347590823749*97098709870985))
I tried replacing 2*m2 with m and got incorrect results. I think this has to do with how the numbers are split but I'm not really sure what's going on.
This goes to the heart of how you split your numbers for the recursive calls.
If you choose to use an odd n then n//2 will be rounded down to the nearest whole number, meaning your second number will have a length of floor(n/2) and you would have to pad the first with the floor(n/2) zeros.
Since we use the same n for both numbers this applies to both. This means if you stick to the original odd n for the final step, you would be padding the first term with the original n zeros instead of the number of zeros that would result from the combination of the first padding plus the second padding (floor(n/2)*2)
You have used m2 as a float. It needs to be an integer.
def karat(x,y):
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
m = max(len(str(x)),len(str(y)))
m2 = m // 2
a = x // 10**(m2)
b = x % 10**(m2)
c = y // 10**(m2)
d = y % 10**(m2)
z0 = karat(b,d)
z1 = karat((a+b),(c+d))
z2 = karat(a,c)
return (z2 * 10**(2*m2)) + ((z1 - z2 - z0) * 10**(m2)) + (z0)
Your code and logic is correct, there is just issue with your base case. Since according to the algo a,b,c,d are 2 digit numbers you should modify your base case and keep the length of x and y equal to 2 in the base case.
I think it is better if you used math.log10 function to calculate the number of digits instead of converting to string, something like this :
def number_of_digits(number):
"""
Used log10 to find no. of digits
"""
if number > 0:
return int(math.log10(number)) + 1
elif number == 0:
return 1
else:
return int(math.log10(-number)) + 1 # Don't count the '-'
The base case if len(str(x)) == 1 or len(str(y)) == 1: return x*y is incorrect. If you run either of the python code given in answers against large integers, the karat() function will not produce the correct answer.
To make the code correct, you need to change the base case to if len(str(x) < 3 or len(str(y)) < 3: return x*y.
Below is a modified implementation of Paul Panzer's answer that correctly multiplies large integers.
def karat(x,y):
if len(str(x)) < 3 or len(str(y)) < 3:
return x*y
n = max(len(str(x)),len(str(y))) // 2
a = x // 10**(n)
b = x % 10**(n)
c = y // 10**(n)
d = y % 10**(n)
z0 = karat(b,d)
z1 = karat((a+b), (c+d))
z2 = karat(a,c)
return ((10**(2*n))*z2)+((10**n)*(z1-z2-z0))+z0

Need help regarding Binary Powering with a matrix

I am trying to write a program that can calculate the nth power of 2x2 matrix using binary powering. I would really appreciate the help. My problem is that the code is only working for a matrix to the power of 2.
def binPow(m,n):
if (n==0): return[[1,0],[0,1]]
q = binPow(m,n//2)
square = MatrMult(o,o)
if (n%2==0):
return square
else:
return MatrMult(m,square)
def MatrMult(o,x):
o = [[b,c],[e,f]]
g = [[(b*b)+(c*e),(b*c)+(c*f)],[(e*b)+(f*e),(e*c)+(f*f)]]
return(g)
b = int(input("Enter A1: "))
c = int(input("Enter A2: "))
e = int(input("Enter A3: "))
f = int(input("Enter A4: "))
o = [[b,c],[e,f]]
n = int(input("Enter Power: "))
print(o, "to the power of", n, " is ", binPow(o,n))
In Python3, n/2 will result in a floating point number. 1/2 is 0.5, 0.5/2 is 0.25, 0.25/2 is 0.125, etc. It never gets to 0, so if (n==0): ... will never execute. To make sure that n is always a whole number, double your slashes: q = binPow(m, n//2). That way, 5//2 becomes 2 instead of 2.5, etc. Your real problem is how you are multiplying the matrices. You are always squaring the original matrix because you don't do anything with the parameters given you. I also took the liberty of modifying your binPow() function to something a little simpler:
def binPow(m,n):
if (n==0): return[[1,0],[0,1]]
q = m
while n > 1:
q = MatrMult(m, q)
n -= 1
return q
def MatrMult(o,x):
((a, b), (c, d)) = o
((e, f), (g, h)) = x
g = [[(a*e)+(b*g),(a*f)+(b*h)],[(c*e)+(d*g),(c*f)+(d*h)]]
return(g)

How to see if a number ends in .0

I am trying to run a test if the number ends in .0
I am running a program with numbers orders of magnitude apart so I can't estimate to a certain amount of digits. using % doesn't work either because then certain numbers are excluded. All the numbers in this program are floating point numbers so I need a way to check if it ends with .0, not with .00000000000001232 or something it has to end exactly in .0
The problem with the round function is that I am dealing with numbers of several orders of magnitude. I need something that checks if it has only 1 decimal after the . or something that checks if the that decimal is a 0.
code:
from myro import *
from math import *
def main():
z = 3
a = 2
b = 2
x = 3
y = 2 #starts at y = 3
lim = 25
c = (a**x + b**y)**(1.0/z)
resultnum = 0
while z <= lim:
while a <= lim:
while b <= lim:
while x <= lim:
while y <= lim:
y = y + 1
c = (a**x + b**y)**(1.0/z)
if float(int(c) + 1) != round(c, 6):
pass
else:
print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(int(c)+1) + "^" + str(z)
resultnum = resultnum + 1
print c
y = 3
x = x + 1
x = 3
b = b + 1
b = 3
a = a + 1
a = 3
z = z + 1
print z
print "code cycle complete"
print str(resultnum) + " results"
main()
>>> n1 = 2.0
>>> int(n1) == n1 and isinstance(n1, float)
True
>>> n1 = 2
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 2.01
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 1E1 #works for scientific notation as well
>>> int(n1) == n1 and isinstance(n1, float)
True
Python does this already. Going with what Python gives as a string might be what you want:
In [577]: def dot_zero(number):
.....: return str(number).endswith('.0')
.....:
In [578]: dot_zero(2.0)
Out[578]: True
In [579]: dot_zero(2)
Out[579]: False
In [580]: dot_zero(2.01)
Out[580]: False
EDIT
As pointed out by #jamylak this does not work for large numbers since the scientific notation used by str. Keeping the basic idea of conversion into a string, but also catering for large numbers, we end up with more verbose and admittedly rather ugly solution:
def dot_zero_string(number):
# tested and works with Python 3.3
split = str(number).split('e')
return len(split) == 2 or split[0].endswith('.0')
This is the solution in the answer from #AshwiniChaudhary
def dot_zero_inst(number):
return int(number) == number and isinstance(number, float)
Comparing different cases gives the same result:
numbers = [1, 1.0, 1000, 1000.0, 3e38, 1.5555555555555555555555e12,
1.5555555555555555555555e17, 0, 0.0]
numbers = numbers + [-number for number in numbers]
for number in numbers:
assert dot_zero_inst(number) == dot_zero_string(number)
Just to show another method, you can always split by the '.':
>>> num = 12.023
>>> str(num).split('.')[1] == '0'
False
>>> num = 12.0
>>> str(num).split('.')[1] == '0'
True
Note that this works because you said that all were floating points. This will provide an error num is an int
x = 26.5
b % math.floor(b) == 0
>>> False
x = 26.0
b % math.floor(b) == 0
>>> True
should also do it.

Categories