首页 > 编程知识 正文

python保留3位有效数字,python保留两位有效数字

时间:2023-05-05 13:36:06 阅读:108192 作者:2767

itaggedthisquestionasjavascriptbecauseeventhoughicurrentlywrotethisinpython,ifitwouldbeeasiertoimplementinjavascript,icoulicoulted

myassignmentistomakeasignificantfigurecalculationcheckerforthechemistrydepartment.whatthansisthestudenterstherstheirdardatment thewebappwillperformpredefinedoperationsontheirfieldsandkeeptrackofsignificantfiguresandseeeiftheiranswerhasthe

whenibroketheproblemdownintowhatifigureisagoodworkflow,irealizedthatiwouldneedawayforeitherpython (thebackendsincethisisawet or JavaScript (causeyoucouldalwaysvalidateitonthefrontendnoproblem ) )。 todeterminethenumberofsignificantdigits.ididalittleresearchandcameacrossthisquestionwhichtellsmethatineededtoworkwithpython ssthon rrentpythoncodefeelsalmostcomplete,butthereisstillonemajorchallengeiface

导入re

deffind_SIGfigs(x ) :

# changethe ' e ' tolowercaseifthestudenttypeditinasuppercase

x=x.lower ()

if(e ) inx ) :

mystr=x.split('e ' ) )。

# thisfunctionassumesthatthenumberontheleftofthe ' e ' is

# thenumberofsigfigs.thatwouldbetrueforuserinputbutnot

# truewhenpythonconvertsafloattoscientificnotation

returnlen((re.search('[0-9] ',myStr[0] ) ).group ) )

else:

# putitineformatandreturntheresultofthat

# # # problem : pythonmakesmehardcodethenumberofsigfigsas '2'

# # # without the2thereitalwaysdefaultsto 6

return find _ SIG figs (“%.* e“%”2,float(x ) x ) )

find_SIGfigs(1.3e-4 ) )

2

find_SIGfigs(1234 ) )。

3

find_SIGfigs(123456 ) )

3

find_SIGfigs(1.2345E3 ) )。

5

then without the 2

return find _ SIG figs (“%.e“%”float ) ) x ) )

# becauseitchangesitto 1.234000 e 3

find_SIGfigs(1234 ) )。

7

# becauseitchangesitto 1.234560 e 5

find_SIGfigs(123456 ) )

7

So simply put,myproblemisthatineedasimplewaytocountthesigfigswhenitisnotexplicitlydeclaredbythestudent . istheresomeeasywaythaticoulddropeveryzerobeforethe ' e ' untilitgetstothefirstnonzerodigit.I guess,inedtostartrtfromthebachebacachbactioromtiomthebactioractioromtinged

edit 3360 soafteralittlemorefiddling,ihopethisisanappropriatesolutiontotheproblem.itesteditseveraltimes,butnotorigorigousssses

deffind_SIGfigs(x ) :

“”returnsthenumberofsignificantdigitsinanumber.thistakesintoaccount

stringsformattedin 1.23 E3 formatandevenstringssuchas 123.450 ' '

# change all the 'E' to 'e '

x=x.lower ()

if(e ) inx ) :

# returnthelengthofthenumbersbeforethe ' e '

mystr=x.split('e ' ) )。

返回len (mystr [0]-1 # tocompenstateforthedecimalpoint

else:

# putitineformatandreturntheresultofthat

### NOTE: because of the 8 below,itmaydocrazythingswhenitparses9SIG figs

n='%.*e'%(8,float(x ) ) ) ).split('e ) ) ) )。

# removeandcountthenumberofremoveduseraddedzeroes.(thesearesigfigs )。

if '.' in x:

s=x.replace '.','')

#number of zeroes to add back in

L=len(s )-len (s.RS trip ) ) '0) )

# stripofthepythonaddedzeroesandaddbackintheonestheuseradded

n[0]=n[0].rstrip('0' ) '.join(['0'fornuminxrange(l ) ]

else:

# theuserhadnotrailingzeroessojuststripthemall

n[0]=n[0].RStrip('0) )。

# passitbacktothebeginningtobeparsed

returnfind_SIGfigs(e'.join () ) )

ithinkregularexpressionsareabitofanoverkillhere,butyourmethodshouldworkandi ' MSU reit ' snotaperformanceissue。

ithink you ' reontherighttrackwithwhatyoudescribeattheend.iwouldusesplit (' e ' ) followedbyRStrip ) '0),whichwilllremove

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。