Exakten Wert beim Quadrieren von Floats (Python)?

Hallo,

heute bin ich mit einem Bug im Rucksack unterwegs.

Ich versuche folgende Zahl 11.313708498984761 in Python zu quadrieren. Das Ergebnis müsste 128 sein, doch er gibt 128,00000000000003 aus und ich verstehe nicht wie ich das präzisieren könnte.

Es wäre schön, falls mir jemand weiterhelfen könnte.

Mit freundlichen Grüßen

JUCEL

PS: Hier mein derzeitiger Code:

# This Script was made to calculate the distance to celestial bodies in space (nearby milkyway).
import math
import decimal
import datetime
import random, string

sin = math.sin;
degrees = math.radians;
decimal.getcontext().prec = 200;
decimal = decimal.Decimal;


# Log-File, Datum, Star-Name

request = input("Hello, please choose between following options:\nDistance-Calculator [1] \nProtokoll [2]\nExit [q]\nOption: ")

if request == str("1"):

    print("Please insert following required data:")

    angle1 = input("Angle 1 (°): ")
    angle2 = input("Angle 2 (°): ")

    distance_In = decimal(input("Distance between the angles (Kilometre): "))



    # Angles

    summary = decimal(angle1) + decimal(angle2)
    angle3 = 180 - float(summary)

    # Distances

    distance_In_parsec = distance_In * decimal(0.000000000000060019)

    # Distance_a

    distance_out_a_parsec = decimal(distance_In) * decimal((sin(degrees(decimal(angle1)))/sin(degrees(decimal(angle3))))) * decimal(0.000000000000060019)
    distance_out_a_ligh_years = decimal(distance_out_a_parsec) * decimal(3.26156)
    distance_out_a_astronomic_unit = decimal(distance_out_a_parsec) * decimal(206265)

    print("Distance a: \n ", distance_out_a_parsec, "parsec \n ", distance_out_a_ligh_years, "ly \n", distance_out_a_astronomic_unit, "AU \n")

    # Distance_b

    distance_out_b_parsec = decimal(distance_In) * decimal((sin(degrees(decimal(angle2)))/sin(degrees(decimal(angle3))))) * decimal(0.000000000000060019)
    distance_out_b_ligh_years = decimal(distance_out_b_parsec) * decimal(3.26156)
    distance_out_b_astronomic_unit = decimal(distance_out_b_parsec) * decimal(206265)

    print("Distance b: \n ", distance_out_b_parsec, "parsec \n ", distance_out_b_ligh_years, "ly \n", distance_out_b_astronomic_unit, "AU \n")

    # Distance_center
    half = decimal(distance_In)/2

    distance_out_center_dump = distance_out_a_parsec * distance_out_a_parsec - half * half

    distance_out_center_parsec = decimal(math.sqrt(abs(decimal(distance_out_center_dump)))) * decimal(0.000000000000060019)
    distance_out_center_light_years = decimal(distance_out_center_parsec) * decimal(3.26156)
    distance_out_center_astronomic_unit = decimal(distance_out_center_parsec) * decimal(206265)

    print("Distance from the center of ellipsis: \n ", distance_out_center_parsec, "parsec \n ", distance_out_center_light_years, "ly \n", distance_out_center_astronomic_unit, "AU")

# Protocol

elif request == str("2"):
    pass

elif request == str("q"):
    exit(0)
Computer, programmieren, Informatik, Python, Python 3
Flächeninhaltrechner in python funktioniert nicht?

Hallo,

Ich programmiere gerade einen Taschenrechner für Flächeninhalte von Formen, den ich immer weiter erweitere, nur irgendwie läuft der Code nicht, und ich glaube es liegt am else, aber wie geht es richtig?

print("Bitte maße mit . eingeben! Zum Beispiel: c = 3,5 cm Gebe ein: 3.5 bei ganzen Zahlen mit .0 angeben \n Zum Beispiel: 3.0")
print("sie können den Flächeninhalt von folgenden Formen berechnen:")
print("Dreieck, Quadrat, Rechteck, Trapez")


Form = input("Von welcher geometrischen Form wollen Sie die den Flächeninhalt berechnen?")


if Form == "Dreieck":
    print("Dreieck berechnen")
    c = float(input("Bitte maße für Grundlinie angeben"))
    h = float(input("Bitte maße für Höhe oder bei rechtwinkligen Seite neben rechten Winkel angeben"))
    Flächeninhalt = 1/2*c*h



elif Form == "Quadrat":
    print("Quadrat berechnen")
    a = float(input("Bitte die Länge einer Seite angeben"))
    Flächeninhalt = a*a



elif Form == "Rechteck":
    print("Quadrat berechnen...")
    a = float(input("Bitte die Länge einer Seite angeben"))
    b = float(input("Bitte die Länge einer danebenliegenden Seite angeben"))
    Flächeninhalt = a*b


else Form == "Trapez":
    print("Trapez berechnen...")
    a = float(input("Bitte Maße der Grundlinie angeben"))
    c = float(input("Bitte Maße der oberen Linie angeben"))
    h = float(input("Bitte Höhe angeben"))
    Flächeninhalt = 1/2*(a+c)*h



print("Flächeninhalt berechnen...")
print(Flächeninhalt)

Danke

programmieren, Python, Python 3
Python wie löse 'NoneType' object is not subscriptable?

Hallo!

Ich schreibe ein kleines Pythonprogramm, das als Web Crawler fungieren soll.Leider erhalte ich in Zeile 36 ein Fehler:

  brand = make_rating_sp[0].img["title"].title()
TypeError: 'NoneType' object is not subscriptable

Leider, finde ich keine Lösung. Wie könnte ich diesen Fehler lösen? Danke im Voraus!

make_rating_sp[0].img is None.

from bs4 import BeautifulSoup as soup  # HTML data structure
from urllib.request import urlopen as uReq  # Web client

# URl to web scrap from.
# in this example we web scrap graphics cards from Newegg.com
page_url = "http://www.newegg.com/Product/ProductList.aspx?Submit=ENE&N=-1&IsNodeId=1&Description=GTX&bop=And&Page=1&PageSize=36&order=BESTMATCH"

# opens the connection and downloads html page from url
uClient = uReq(page_url)

# parses html into a soup data structure to traverse html
# as if it were a json data type.
page_soup = soup(uClient.read(), "html.parser")
uClient.close()

# finds each product from the store page
containers = page_soup.findAll("div", {"class": "item-container"})

# name the output file to write to local disk
out_filename = "graphics_cards.csv"
# header of csv file to be written
headers = "brand,product_name,shipping \n"

# opens file, and writes headers
f = open(out_filename, "w")
f.write(headers)

# loops over each product and grabs attributes about
# each product
for container in containers:
    # Finds all link tags "a" from within the first div.
    make_rating_sp = container.div.select("a")

    # Grabs the title from the image title attribute
    # Then does proper casing using .title()
    brand = make_rating_sp[0].img["title"].title()

    # Grabs the text within the second "(a)" tag from within
    # the list of queries.
    product_name = container.div.select("a")[2].text

    # Grabs the product shipping information by searching
    # all lists with the class "price-ship".
    # Then cleans the text of white space with strip()
    # Cleans the strip of "Shipping $" if it exists to just get number
    shipping = container.findAll("li", {"class": "price-ship"})[0].text.strip().replace("$", "").replace(" Shipping", "")

    # prints the dataset to console
    print("brand: " + brand + "\n")
    print("product_name: " + product_name + "\n")
    print("shipping: " + shipping + "\n")

    # writes the dataset to file
    f.write(brand + ", " + product_name.replace(",", "|") + ", " + shipping + "\n")

f.close()  # Close the file
programmieren, Informatik, Python, Python 3
Pygame hängt sich bei while True: loop auf?

Hallo,

ich programmiere gerade ein Spiel in Pygame. Auf jeden Fall möchte ich den Ninja Wurfsternen (&anderen Waffen)Ammo geben, dass man eine bestimmte Anzahl von diesen hat und diese nicht spammen kann. Wenn man Space drückt, wird der Ammo Variable eins abgezogen und wenn der Ammo (heißt es der Ammo? ) höher als 0 ist, wird der Befehl self.shoot() ausgeführt. Jetzt mein Problem: Egal, welche Nummer die Variable hat (außer Null), kann ich einmal schießen und danach nicht mehr, auch wenn ich Space drücke. Ich weiß nur nicht wieso. Wenn ich es in einen while True, loop packe, hängt sich pygame auf. Nur wie kann ich das fixen, dass ich öfter als 1 Mal schießen kann. Hier mein benötigter Code (ohne den While True loop):

class Player(pg.sprite.Sprite):

def __init__(self, game, x, y):

self.weapon = 'blowpipe'

self.shurikan = False

self.blowpipe = False

self.xp = PLAYER_XP

self.shoot_ammo = True

self.BLOWPIPE_AMMO = 5

self.SHURIKAN_AMMO = 5

def get_keys(self):

keys = pg.key.get_pressed()

if keys[pg.K_SPACE]:

if self.weapon == 'blowpipe' and self.shoot_ammo == True:

self.BLOWPIPE_AMMO -= 1

if self.BLOWPIPE_AMMO < 0:

self.BLOWPIPE_AMMO = 0

if self.BLOWPIPE_AMMO == 0:

self.shoot_ammo = False

if self.BLOWPIPE_AMMO > 0:

self.shoot()

if self.weapon == 'shurikan' and self.shoot_ammo == True:

self.SHURIKAN_AMMO -= 1

if self.SHURIKAN_AMMO < 0:

self.SHURIKAN_AMMO = 0

if self.SHURIKAN_AMMO == 0:

self.shoot_ammo = False

if self.SHURIKAN_AMMO > 0:

self.shoot()

def shoot(self):

if self.shoot_ammo == True:

now = pg.time.get_ticks()

if now - self.last_shot > WEAPONS[self.weapon]['rate']:

self.last_shot = now

dir = vec(1, 0).rotate(-self.rot)

EinegleicheListegibtesfürBlowpipe.

pos = self.pos + BARREL_OFFSET.rotate(-self.rot)

self.vel = vec(-WEAPONS[self.weapon]['rate'], 0).rotate(-self.rot)

for i in range(WEAPONS[self.weapon]['count']):

spread = uniform(-WEAPONS[self.weapon]['spread'], WEAPONS[self.weapon]['spread'])

Blowpipe(self.game, pos, dir.rotate(spread))

Außerdem gibt es eine Weapons Liste in einem anderen File:

WEAPONS['blowpipe'] = {'img': 'blowpipe.png',

'speed': 500,

'lifetime': 600,

'rate': 300,

'kickback': 0,

'spread': 5,

'damage': 3,

'size': 'blowpipe',

'count': 1}

Eine ähnliche Liste benutze ich für den Shurikan. Thx

Computer, Mac, programmieren, Informatik, Python, Python 3, Pygame, VS Code

Meistgelesene Beiträge zum Thema Python 3