首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python中循环计数时的错误inf

python中循环计数时的错误inf
EN

Stack Overflow用户
提问于 2022-02-25 13:20:24
回答 1查看 49关注 0票数 -3
代码语言:javascript
复制
import matplotlib.pyplot as plt
import math
lista=["which",
"there",
"their",
"about",
"would",
"these",
"other",
"words",
"could",
"write",
"first",
"water",
"after",
"where",
"right",
"think",
"three",
"years",
"place",
"sound",
"great",
"again",
"still",
"every",
"small",
"found",
"those",
"never",
"under",
"might",
"while",
"house",
"world",
"below",
"asked",
"going",
"large",
"until",
"along",
"shall",
"being",
"often",
"earth",
"began",
"since",
"study",
"night",
"light",
"above",
"paper",
"parts",
"young",
"story",
"point",
"times",
"heard",
"whole",
"white",
"given",
"means",
"music",
"miles",
"thing",
"today",
"later",
"using",
"money",
"lines",
"order",
"group",
"among",
"learn",
"known",
"space",
"table",
"early",
"trees",
"short",
"hands",
"state",
"black",
"shown",
"stood",
"front",
"voice",
"kinds",
"makes",
"comes",
"close",
"power",
"lived",
"vowel",
"taken",
"built",
"heart",
"ready",
"quite",
"class",
"bring",
"round",
"horse",
"shows",
"piece",
"green",
"stand",
"birds",
"start",
"river",
"tried",
"least",
"field",
"whose",
"girls",
"leave",
"added",
"color",
"third",
"hours",
"moved",
"plant",
"doing",
"names",
"forms",
"heavy",
"ideas",
"cried",
"check",
"floor",
"begin",
"woman",
"alone",
"plane",
"spell",
"watch",
"carry",
"wrote",
"clear",
"named",
"books",
"child",
"glass",
"human",
"takes",
"party",
"build",
"seems",
"blood",
"sides",
"seven",
"mouth",
"solve",
"north",
"value",
"death",
"maybe",
"happy",
"tells",
"gives",
"looks",
"shape",
"lives",
"steps",
"areas",
"sense",
"speak",
"force",
"ocean",
"speed",
"women",
"metal",
"south",
"grass",
"scale",
"cells",
"lower",
"sleep",
"wrong",
"pages",
"ships",
"needs",
"rocks",
"eight",
"major",
"level",
"total",
"ahead",
"reach",
"stars",
"store",
"sight",
"terms",
"catch",
"works",
"board",
"cover",
"songs",
"equal",
"stone",
"waves",
"guess",
"dance",
"spoke",
"break",
"cause",
"radio",
"weeks",
"lands",
"basic",
"liked",
"trade",
"fresh",
"final",
"fight",
"meant",
"drive",
"spent",
"local",
"waxes",
"knows",
"train",
"bread",
"homes",
"teeth",
"coast",
"thick",
"brown",
"clean",
"quiet",
"sugar",
"facts",
"steel",
"forth",
"rules",
"notes",
"units",
"peace",
"month",
"verbs",
"seeds",
"helps",
"sharp",
"visit",
"woods",
"chief",
"walls",
"cross",
"wings",
"grown",
"cases",
"foods",
"crops",
"fruit",
"stick",
"wants",
"stage",
"sheep",
"nouns",
"plain",
"drink",
"bones",
"apart",
"turns",
"moves",
"touch",
"angle",
"based",
"range",
"marks",
"tired",
"older",
"farms",
"spend",
"shoes",
"goods",
"chair",
"twice",
"cents",
"empty",
"alike",
"style",
"broke",
"pairs",
"count",
"enjoy",
"score",
"shore",
"roots",
"paint",
"heads",
"shook",
"serve",
"angry",
"crowd",
"wheel",
"quick",
"dress",
"share",
"alive",
"noise",
"solid",
"cloth",
"signs",
"hills",
"types",
"drawn",
"worth",
"truck",
"piano",
"upper",
"loved",
"usual",
"faces",
"drove",
"cabin",
"boats",
"towns",
"proud",
"court",
"model",
"prime",
"fifty",
"plans",
"yards",
"prove",
"tools",
"price",
"sheet",
"smell",
"boxes",
"raise",
"match",
"truth",
"roads",
"threw",
"enemy",
"lunch",
"chart",
"scene",
"graph",
"doubt",
"guide",
"winds",
"block",
"grain",
"smoke",
"mixed",
"games",
"wagon",
"sweet",
"topic",
"extra",
"plate",
"title",
"knife",
"fence",
"falls",
"cloud",
"wheat",
"plays",
"enter",
"broad",
"steam",
"atoms",
"press",
"lying",
"basis",
"clock",
"taste",
"grows",
"thank",
"storm",
"agree",
"brain",
"track",
"smile",
"funny",
"beach",
"stock",
"hurry",
"saved",
"sorry",
"giant",
"trail",
"offer",
"ought",
"rough",
"daily",
"avoid",
"keeps",
"throw",
"allow",
"cream",
"laugh",
"edges",
"teach",
"frame",
"bells",
"dream",
"magic",
"occur",
"ended",
"chord",
"false",
"skill",
"holes",
"dozen",
"brave",
"apple",
"climb",
"outer",
"pitch",
"ruler",
"holds",
"fixed",
"costs",
"calls",
"blank",
"staff",
"labor",
"eaten",
"youth",
"tones",
"honor",
"globe",
"gases",
"doors",
"poles",
"loose",
"apply",
"tears",
"exact",
"brush",
"chest",
"layer",
"whale",
"minor",
"faith",
"tests",
"judge",
"items",
"worry",
"waste",
"hoped",
"strip",
"begun",
"aside",
"lakes",
"bound",
"depth",
"candy",
"event",
"worse",
"aware",
"shell",
"rooms",
"ranch",
"image",
"snake",
"aloud",
"dried",
"likes",
"motor",
"pound",
"knees",
"refer",
"fully",
"chain",
"shirt",
"flour",
"drops",
"spite",
"orbit",
"banks",
"shoot",
"curve",
"tribe",
"tight",
"blind",
"slept",
"shade",
"claim",
"flies",
"theme",
"queen",
"fifth",
"union",
"hence",
"straw",
"entry",
"issue",
"birth",
"feels",
"anger",
"brief",
"rhyme",
"glory",
"guard",
"flows",
"flesh",
"owned",
"trick",
"yours",
"sizes",
"noted",
"width",
"burst",
"route",
"lungs",
"uncle",
"bears",
"royal",
"kings",
"forty",
"trial",
"cards",
"brass",
"opera",
"chose",
"owner",
"vapor",
"beats",
"mouse",
"tough",
"wires",
"meter",
"tower",
"finds",
"inner",
"stuck",
"arrow",
"poems",
"label",
"swing",
"solar",
"truly",
"tense",
"beans",
"split",
"rises",
"weigh",
"hotel",
"stems",
"pride",
"swung",
"grade",
"digit",
"badly",
"boots",
"pilot",
"sales",
"swept",
"lucky",
"prize",
"stove",
"tubes",
"acres",
"wound",
"steep",
"slide",
"trunk",
"error",
"porch",
"slave",
"exist",
"faced",
"mines",
"marry",
"juice",
"raced",
"waved",
"goose",
"trust",
"fewer",
"favor",
"mills",
"views",
"joint",
"eager",
"spots",
"blend",
"rings",
"adult",
"index",
"nails",
"horns",
"balls",
"flame",
"rates",
"drill",
"trace",
"skins",
"waxed",
"seats",
"stuff",
"ratio",
"minds",
"dirty",
"silly",
"coins",
"hello",
"trips",
"leads",
"rifle",
"hopes",
"bases",
"shine",
"bench",
"moral",
"fires",
"meals",
"shake",
"shops",
"cycle",
"movie",
"slope",
"canoe",
"teams",
"folks",
"fired",
"bands",
"thumb",
"shout",
"canal",
"habit",
"reply",
"ruled",
"fever",
"crust",
"shelf",
"walks",
"midst",
"crack",
"print",
"tales",
"coach",
"stiff",
"flood",
"verse",
"awake",
"rocky",
"march",
"fault",
"swift",
"faint",
"civil",
"ghost",
"feast",
"blade",
"limit",
"germs",
"reads",
"ducks",
"dairy",
"worst",
"gifts",
"lists",
"stops",
"rapid",
"brick",
"claws",
"beads",
"beast",
"skirt",
"cakes",
"lions",
"frogs",
"tries",
"nerve",
"grand",
"armed",
"treat",
"honey",
"moist",
"legal",
"penny",
"crown",
"shock",
"taxes",
"sixty",
"altar",
"pulls",
"sport",
"drums",
"talks",
"dying",
"dates",
"drank",
"blows",
"lever",
"wages",
"proof",
"drugs",
"tanks",
"sings",
"tails",
"pause",
"herds",
"arose",
"hated",
"clues",
"novel",
"shame",
"burnt",
"races",
"flash",
"weary",
"heels",
"token",
"coats",
"spare",
"shiny",
"alarm",
"dimes",
"sixth",
"clerk",
"mercy",
"sunny",
"guest",
"float",
"shone",
"pipes",
"worms",
"bills",
"sweat",
"suits",
"smart",
"upset",
"rains",
"sandy",
"rainy",
"parks",
"sadly",
"fancy",
"rider",
"unity",
"bunch",
"rolls",
"crash",
"craft",
"newly",
"gates",
"hatch",
"paths",
"funds",
"wider",
"grace",
"grave",
"tides",
"admit",
"shift",
"sails",
"pupil",
"tiger",
"angel",
"cruel",
"agent",
"drama",
"urged",
"patch",
"nests",
"vital",
"sword",
"blame",
"weeds",
"screw",
"vocal",
"bacon",
"chalk",
"cargo",
"crazy",
"acted",
"goats",
"arise",
"witch",
"loves",
"queer",
"dwell",
"backs",
"ropes",
"shots",
"merry",
"phone",
"cheek",
"peaks",
"ideal",
"beard",
"eagle",
"creek",
"cries",
"ashes",
"stall",
"yield",
"mayor",
"opens",
"input",
"fleet",
"tooth",
"cubic",
"wives",
"burns",
"poets",
"apron",
"spear",
"organ",
"cliff",
"stamp",
"paste",
"rural",
"baked",
"chase",
"slice",
"slant",
"knock",
"noisy",
"sorts",
"stays",
"wiped",
"blown",
"piled",
"clubs",
"cheer",
"widow",
"yukky",
"styes",
"waker",
"flaks",
"maces",
"rimes",
"gimpy",
"guano",
"liras",
"kapok",
"scuds",
"bwana",
"oring",
"aider",
"prier",
"klugy",
"monte",
"golem",
"velar",
"firer",
"pieta",
"umbel",
"campo",
"unpeg",
"fovea",
"abeam",
"boson",
"asker",
"goths",
"vocab",
"vined",
"trows",
"tikis",
"loper",
"indie",
"boffs",
"spang",
"grapy",
"tater",
"ichor",
"kilty",
"lochs",
"supes",
"degas",
"flics",
"torsi",
"beths",
"weber",
"resaw",
"lawny",
"coven",
"mujik",
"relet",
"therm",
"heigh",
"shnor",
"trued",
"zayin",
"liest",
"barfs",
"bassi",
"qophs",
"roily",
"flabs",
"punny",
"okras",
"hanks",
"dipso",
"nerfs",
"fauns",
"calla",
"pseud",
"lurer",
"magus",
"obeah",
"atria",
"twink",
"palmy",
"pocky",
"pends",
"recta",
"plonk",
"slaws",
"keens",
"nicad",
"pones",
"inker",
"whews",
"groks",
"mosts",
"trews",
"ulnar",
"gyppy",
"cocas",
"expos",
"eruct",
"oiler",
"vacua",
"dreck",
"dater",
"arums",
"tubal",
"voxel",
"dixit",
"beery",
"assai",
"lades",
"actin",
"ghoti",
"buzzy",
"meads",
"grody",
"ribby",
"clews",
"creme",
"email",
"pyxie",
"kulak",
"bocci",
"rived",
"duddy",
"hoper",
"lapin",
"wonks",
"petri",
"phial",
"fugal",
"holon",
"boomy",
"duomo",
"musos",
"shier",
"hayer",
"porgy",
"hived",
"litho",
"fisty",
"stagy",
"luvya",
"maria",
"smogs",
"asana",
"yogic",
"slomo",
"fawny",
"amine",
"wefts",
"gonad",
"twirp",
"brava",
"plyer",
"fermi",
"loges",
"niter",
"revet",
"unate",
"gyved",
"totty",
"zappy",
"honer",
"giros",
"dicer",
"calks",
"luxes",
"monad",
"cruft",
"quoin",
"fumer",
"amped",
"shlep",
"vinca",
"yahoo",
"vulva",
"zooey",
"dryad",
"nixie",
"moper",
"iambs",
"lunes",
"nudie",
"limns",
"weals",
"nohow",
"miaow",
"gouts",
"mynas",
"mazer",
"kikes",
"oxeye",
"stoup",
"jujus",
"debar",
"pubes",
"taels",
"defun",
"rands",
"blear",
"paver",
"goosy",
"sprog",
"oleos",
"toffy",
"pawer",
"maced",
"crits",
"kluge",
"tubed",
"sahib",
"ganef",
"scats",
"sputa",
"vaned",
"acned",
"taxol",
"plink",
"oweth",
"tribs",
"resay",
"boule",
"thous",
"haply",
"glans",
"maxis",
"bezel",
"antis",
"porks",
"quoit",
"alkyd",
"glary",
"beamy",
"hexad",
"bonks",
"tecum",
"kerbs",
"filar",
"frier",
"redux",
"abuzz",
"fader",
"shoer",
"couth",
"trues",
"guyed",
"goony",
"booky",
"fuzes",
"hurly",
"genet",
"hodad",
"calix",
"filer",
"pawls",
"iodic",
"utero",
"henge",
"unsay",
"liers",
"piing",
"weald",
"sexed",
"folic",
"poxed",
"cunts",
"anile",
"kiths",
"becks",
"tatty",
"plena",
"rebar",
"abled",
"toyer",
"attar",
"teaks",
"aioli",
"awing",
"anent",
"feces",
"redip",
"wists",
"prats",
"mesne",
"muter",
"smurf",
"owest",
"bahts",
"lossy",
"ftped",
"hunky",
"hoers",
"slier",
"sicks",
"fatly",
"delft",
"hiver",
"himbo",
"pengo",
"busks",
"loxes",
"zonks",
"ilium",
"aport",
"ikons",
"mulct",
"reeve",
"civvy",
"canna",
"barfy",
"kaiak",
"scudo",
"knout",
"gaper",
"bhang",
"pease",
"uteri",
"lases",
"paten",
"rasae",
"axels",
"stoas",
"ombre",
"styli",
"gunky",
"hazer",
"kenaf",
"ahoys",
"ammos",
"weeny",
"urger",
"kudzu",
"paren",
"bolos",
"fetor",
"nitty",
"techy",
"lieth",
"somas",
"darky",
"villi",
"gluon",
"janes",
"cants",
"farts",
"socle",
"jinns",
"ruing",
"slily",
"ricer",
"hadda",
"wowee",
"rices",
"nerts",
"cauls",
"swive",
"lilty",
"micks",
"arity",
"pasha",
"finif",
"oinky",
"gutty",
"tetra",
"wises",
"wolds",
"balds",
"picot",
"whats",
"shiki",
"bungs",
"snarf",
"legos",
"dungs",
"stogy",
"berms",
"tangs",
"vails",
"roods",
"morel",
"sware",
"elans",
"latus",
"gules",
"razer",
"doxie",
"buena",
"overs",
"gutta",
"zincs",
"nates",
"kirks",
"tikes",
"donee",
"jerry",
"mohel",
"ceder",
"doges",
"unmap",
"folia",
"rawly",
"snark",
"topoi",
"ceils",
"immix",
"yores",
"diest",
"bubba",
"pomps",
"forky",
"turdy",
"lawzy",
"poohs",
"worts",
"gloms",
"beano",
"muley",
"barky",
"tunny",
"auric",
"funks",
"gaffs",
"cordy",
"curdy",
"lisle",
"toric",
"soyas",
"reman",
"mungy",
"carpy",
"apish",
"oaten",
"gappy",
"aurae",
"bract",
"rooky",
"axled",
"burry",
"sizer",
"proem",
"turfy",
"impro",
"mashy",
"miens",
"nonny",
"olios",
"grook",
"sates",
"agley",
"corgi",
"dashy",
"doser",
"dildo",
"apsos",
"xored",
"laker",
"playa",
"selah",
"malty",
"dulse",
"frigs",
"demit",
"whoso",
"rials",
"sawer",
"spics",
"bedim",
"snugs",
"fanin",
"azoic",
"icers",
"suers",
"wizen",
"koine",
"topos",
"shirr",
"rifer",
"feral",
"laded",
"lased",
"turds",
"swede",
"easts",
"cozen",
"unhit",
"pally",
"aitch",
"sedum",
"coper",
"ruche",
"geeks",
"swags",
"etext",
"algin",
"offed",
"ninja",
"holer",
"doter",
"toter",
"besot",
"dicut",
"macer",
"peens",
"pewit",
"redox",
"poler",
"yecch",
"fluky",
"doeth",
"twats",
"cruds",
"bebug",
"bider",
"stele",
"hexer",
"wests",
"gluer",
"pilau",
"abaft",
"whelm",
"lacer",
"inode",
"tabus",
"gator",
"cuing",
"refly",
"luted",
"cukes",
"bairn",
"bight",
"arses",
"crump",
"loggy",
"blini",
"spoor",
"toyon",
"harks",
"wazoo",
"fenny",
"naves",
"keyer",
"tufas",
"morph",
"rajas",
"typal",
"spiff",
"oxlip",
"unban",
"mussy",
"finny",
"rimer",
"login",
"molas",
"cirri",
"huzza",
"agone",
"unsex",
"unwon",
"peats",
"toile",
"zombi",
"dewed",
"nooky",
"alkyl",
"ixnay",
"dovey",
"holey",
"cuber",
"amyls",
"podia",
"chino",
"apnea",
"prims",
"lycra",
"johns",
"primo",
"fatwa",
"egger",
"hempy",
"snook",
"hying",
"fuzed",
"barms",
"crink",
"moots",
"yerba",
"rhumb",
"unarc",
"direr",
"munge",
"eland",
"nares",
"wrier",
"noddy",
"atilt",
"jukes",
"ender",
"thens",
"unfix",
"doggo",
"zooks",
"diddy",
"shmoo",
"brusk",
"prest",
"curer",
"pasts",
"kelpy",
"bocce",
"kicky",
"taros",
"lings",
"dicky",
"nerdy",
"abend",
"stela",
"biggy",
"laved",
"baldy",
"pubis",
"gooks",
"wonky",
"stied",
"hypos",
"assed",
"spumy",
"osier",
"roble",
"rumba",
"biffy",
"pupal"]
#SETTING LIST OF OPTIONS
guess="which"
listofoptions=[]
entrophies={}
possibleoptions={"G","W","Y"}
for i in possibleoptions:
    for j in possibleoptions:
        for k in possibleoptions:
            for l in possibleoptions:
                for m in possibleoptions:
                    possibility=[i,j,k,l,m]
                    listofoptions.append(possibility)
#for i in range(len(listofoptions)):
    #print(i+1,listofoptions[i])
listofoptionsstring=[]
for i in range(len(listofoptions)):
    string=""
    for j in range(5):
        string+=listofoptions[i][j]
    listofoptionsstring.append(string)

dictionaryofoptions= {i : 0 for i in listofoptionsstring}
print(dictionaryofoptions)


#SET pattern between solution and guess word
def SetPattern(string,solution):
    accuratecolor=""
    for i in range(len(string)):
        if string[i]=="":
            accuratecolor+="W"
        elif string[i] in solution:
            if string[i] == solution[i]:
                accuratecolor+="G"
            else:
                accuratecolor+="Y"
        else:
            accuratecolor+="W"
    return accuratecolor


def NumberofPatterns(pattern):
    dictionaryofoptions[pattern]=dictionaryofoptions[pattern]+1     

for j in range(0,100,1):
    for i in lista:
        pattern=SetPattern(lista[j],i)
        NumberofPatterns(pattern)
    print(f'Finished {j+1}/5757 words')
    for k in dictionaryofoptions:
        dictionaryofoptions[k]=dictionaryofoptions[k]/5757
    entrophy=0
    for k in dictionaryofoptions:
        print(f'{j} Entrophy: {entrophy}')
        if dictionaryofoptions[k]!=0:
            print("Not zero")
            entrophy+=dictionaryofoptions[k]*math.log(1/dictionaryofoptions[k],2)
        else:
            print("Zero")
            entrophy+=0
    entrophies[lista[j]]=entrophy
    print(entrophies[lista[j]])

sort_orders = sorted(entrophies.items(), key=lambda x: x[1], reverse=True)
for i in range(10):
    print(sort_orders[i][0],sort_orders[i][1])

我的程序是计算单词的含义,它们在语言游戏中的信息量有多大。我的问题是,在点票过程中,特别是这部分:

代码语言:javascript
复制
for k in dictionaryofoptions:
        print(f'{j} Entrophy: {entrophy}')
        if dictionaryofoptions[k]!=0:
            print("Not zero")
            entrophy+=dictionaryofoptions[k]*math.log(1/dictionaryofoptions[k],2)
        else:
            print("Zero")
            entrophy+=0

它给一些词带来了一个错误,就好像它们的纠缠是无限的。我可以看到,他们正在被计数到一定程度,但后来的准确性是低的,他们变成了inf。然而,当在循环之外计算这个单词时,单独计算,它们就被计算得更多了。我不知道如何纠正这个错误。

EN

回答 1

Stack Overflow用户

发布于 2022-02-25 13:33:24

问题是,您有一个非零数的f,所以1/finf

代码语言:javascript
复制
f = 1.3916074e-316
print(f, 1/f)

1.3916074e-316 inf

你可以用

代码语言:javascript
复制
entrophy-=dictionaryofoptions[k]*math.log(dictionaryofoptions[k],2)

PS.:你可能不应该在你的字典选项中有这个值,也许那是因为你反复被5757除法。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71266490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档