Surviving in Canton Zurich

Last updated: 3rd March 2023

Everyone wants to move to Switzerland.

  • It’s consistently ranked as one of the top countries in the world in terms of quality of life.
  • The nature is breath-taking.
  • Things tend to be well-organised.
  • It is very safe and crime is minimal.

Yet, moving to Switzerland is very hard for a number of reasons, including:

  • It is hard to find accurate information on how things work beyond the happy-go-lucky blog posts.
  • The language barrier means that a lot of official information is in languages one might not understand.
  • Switzerland is isolated in many ways: it is not part of the EU, has its own currency, is not part of the common European mobile network, etc.
  • Life in Switzerland can be rather different from what one is used to, and it takes some adjustment.

In this post, I hope to share what it’s really like to move to Switzerland. I’m not going to write about the pros and cons of living in Switzerland as that’s entirely subjective and not very useful. This is just the information I wish I had before moving. At a high level, I cover the following areas:

  • Settling In: Important things to do immediately before and after you arrive in Switzerland
  • Domestic Life: What living in a Swiss apartment is like
  • How Things Work: Information about systems such as transport, healthcare and more
  • Real Problems: Bigger-picture situations you should be aware of
  • Myths: Common misconceptions
  • Long-Term Considerations: settling permanently or leaving Switzerland

Full disclosure: I have been in Switzerland for less than a year, so I can’t talk extensively about certain aspects of Swiss life. However, my experience is fresh enough that it can be quite useful for newcomers. Also, this information is specific to living in or near Zurich, as different regions (cantons) have their own rules. Where I recommend or don’t recommend specific companies, this is down to my own subjective experience that I had while using them; it doesn’t mean I’ve tried other options and I don’t earn any commission from this. I am not a lawyer, tax accountant or Swiss government official so you should always seek professional advice when in doubt.

See also “Surprising Swiss Trivia” for other interesting tidbits about Switzerland that don’t belong in this article.

Settling In

So you’ve decided to move to Switzerland. There are a number of things you need to do first.

Use Comparis to compare options whenever you have to choose a company for a service (e.g. bank, ISP, etc).

A Swiss Job

Before you move to Switzerland, you need to have a job offer from a Swiss company. While in theory it might be possible (I don’t know) to live in Switzerland while working for a foreign company, you’re unlikely to survive financially unless you’re on a very high salary, and the tax implications may be complex and costly.

Bring With You

Before moving to Switzerland, it’s good to bring with you:

  • Copies of your work contract
  • Passport-size photos

Also, turn off your mobile data before you arrive in Switzerland unless you’ve specifically bought some mobile pack that gives you connectivity in Switzerland. Switzerland is not part of EU Zone 1, and data roaming is expensive enough to burn through your credit with a couple of megabytes.

Your First Address

When booking your first (temporary) accommodation in Switzerland, make sure you book it for about 6 weeks, and that you have an address in your name so that you can receive mail via the postal system.

The reason for this is because when you register (see next subsection) with the authorities, it will take a few weeks to get your official documents (including your permit) and they will arrive by post. You will also need to receive other things by post (e.g. your bank card).

A common suggestion I’ve seen on some websites is to go with Vision Apartments, but I have had a terrible experience with them (it would take an entire article to get into the details) and so have some friends of mine, so I don’t recommend Vision Apartments. I’m not really sure what other options there are, but I’ve known some people to use Airbnbs or a sublet. Whatever it is, make sure you have an address.

Interestingly, while subletting is legal in Switzerland (assuming the tenancy contract allows it), tenants can’t make a profit from subletting. And since sublets tend to be short-term, fixed-duration arrangements to cover a tenant’s period of absence, it can be a reasonable arrangement as a first accommodation.

Also, it helps to find something as central as possible at the beginning, even if it might cost more. You’ll be running around a lot to get things sorted as well as to find an apartment, so being close to the Zurich HB (central station) will save you both time and transport costs.

Registration

The first thing you need to do is visit the local city authorities and register. That would be the nearest Kreisbüro if you’re in Zurich, or the Gemeinde if you’re in some village outside of Zurich. They typically speak multiple languages including English, so you probably won’t have problems.

The requirements for registration vary depending on where you come from. For EU citizens it’s pretty easy and results in what is called the B permit, which is valid for 5 years and can be renewed (see “Getting the C Permit” for more information about this topic).

You’ll need to take some things with you including:

  • Your passport
  • Proof of your current address
  • A copy of your work contract
  • Cash or credit card (you’ll need to pay a fee)

I’m not sure whether that’s everything, so check with them to see whether they need anything else.

While you’re there, you should also:

  • Ask any questions you may have about the registration process
  • Ask for an “extract from the debt collection register” – you’ll need this soon (see “Finding an Apartment”)

The authorities will give you on the spot:

  • A confirmation of residence permit. This is a temporary document in lieu of your residence permit until you receive it. It is very important and required for some of the next steps.
  • An appointment to have your photo taken for the residence permit.

Bank Account

Banking is one of the things that Swizerland is most known for, so it stands to reason that there are lots of banks you can choose from. They can vary a lot in terms of:

  • Language: Some banks will provide correspondence in any language whereas others will be only in German.
  • Geographical coverage: Some are nationwide (e.g. Credit Suisse, UBS, etc) whereas others operate only in specific cantons (e.g. Zürcher Kantonalbank) or municipalities (e.g. Bank of Thalwil).
  • Product offering and charges

So you should do your research and figure out what’s best for you. I recommend Credit Suisse because I had a very good experience with them: (a) their CSX product is a very good bank account in CHF with virtually no charges (just something minimal when you withdraw cash – something I’ve never needed to do); (b) their online portal and mobile app are very stable and user-friendly; (c) their Europallee branch is very central and is open even on Saturdays; (d) their staff are helpful and friendly; (e) they are nationwide.

SBB Half Fare

One of the first things you should do is go to SBB (the Swiss public transport company – they have a big customer service centre at the Zurich HB) and apply for the half fare.

Take with you:

  • Your confirmation of residence permit (serves as proof of address)
  • A passport-size photo
  • Cash or credit card

You pay something like 180 CHF (at the time of writing this), but every trip you make on public transport (trains, buses, trams, ferries and even some funiculars) will then be at half price. Given that even short trips can cost around 20 CHF or more, and that you’ll be running around a lot to see apartments in different areas, this pays for itself very quickly and you save a lot of money in the long run, even if you work remotely and don’t have to commute to work.

If, on the other hand, your employer gives you some kind of SBB pass as a benefit, then you might not need to get the half fare.

Health Insurance

By law, you have to get a health insurance within 3 months of arriving in Switzerland. Again, there are lots of providers you can choose from; I recommend CSS because (a) they speak English; (b) they are friendly and helpful; (c) I was able to do everything over the phone. Once you have a health insurance provider, you need to take the confirmation of health insurance to the local authorities where you’re living to prove that you’ve fulfilled this obligation.

The health insurance subscription is backdated from the day you arrived in Switzerland, so this means that:

  • You don’t save anything by taking a health insurance later rather than sonner.
  • If you incur medical costs before you have a health insurance, you’re still covered and can claim them once you have a health insurance.

As health insurance is a legal requirement, companies can’t simply refuse to insure you (e.g. due to pre-existing medical conditions).

See “Healthcare” for more information on this topic.

Mobile Connectivity

While it’s possible to keep using your foreign mobile number, it’s more practical to get a Swiss phone number. Switzerland’s mobile network is not part of EU Zone 1, and that means that whatever packs you’re paying for to get free calls or data while roaming don’t apply in Switzerland. It’s easy to burn a lot of money on international phone calls (from your foreign mobile number to Swiss companies) and data roaming.

Once again, there are lots of options and I’m not going to make recommendations in this case. However, some things you should consider include:

  • Most providers seem to offer contracts involving monthly payments. However, it’s still possible to find prepaid mobile services which provide more control over which pack you’re paying for and when you want to stop using it.
  • Most providers offer calls, SMSes and data within Switzerland only, but some do offer packs that include limited coverage within the EU as well. If you need to call your home country often, this could be a useful thing to have.

Finding an Apartment

Finding an apartment in Switzerland is literally like applying for a job. You need to compete with lots of other people, do all you can to convince the landlord or management company that you’re a reliable tenant, and then hope that you get chosen. As a result, the approach you should take is quite similar to job hunting as well:

  1. Go on a site like Homegate and look for properties based on criteria you’re interested in (more on this below).
  2. Keep a spreadsheet to keep track of the ones you’re interested, their features, and what stage you got to in the application process.
  3. Contact the advertiser of the ones you’re interested in, to hopefully get to a viewing.
  4. Go and see the apartment. Ask questions on the things that are important for you, take a good look around, and pick up an application form if you’re interested. Sometimes you will see an apartment that a tenant is still living in. In this case, be sure to take off your shoes as you enter.
  5. Apply to the properties you’re really interested in (multiple ones) and provide the following (you can usually do this via email):
    1. The filled in application form.
    2. A copy of your work contract (there is no such thing as privacy – you are at their mercy).
    3. A copy of your passport.
    4. A copy of your (comfirmation of) residence permit.
    5. A copy of your “extract from the debt collection register” (obtainable from the Kreisbüro/Gemeinde which is cheaper than Homegate’s “Simple and fast” offering)
    6. A cover letter outlining what a great tenant you are and why they would be lucky to have you.

Some criteria to consider when looking for/at apartments include:

  • Owner: most apartments are run by management companies, but you’ll find a few owned by private landlords. The latter might be more reachable in case of questions and problems, especially if they live nearby.
  • Availability: Most apartments’ availability align with the official Swiss moving dates (1st April, 1st July and 1st October), but a few are available immediately or between those dates. The timing can be very important depending on your agreement with your temporary accommodation.
  • Cost: obviously, you have to consider how much the rent will cost you. But, apartments also have different agreements depending on what additional costs you need to pay, e.g. heating, electricity, garbage disposal, water, etc.
  • Rooms: Switzerland uses a complicated system where you’ll often see something like “2.5 rooms” rather than “1 bedroom and 1 bathroom”. The meaning of this number is a little arbitrary, but my general rule of thumb is: number of bedrooms = number of rooms – 1.5. This means that a 3.5-room apartment has 2 bedrooms, although keep in mind that this is not always the case. Anyway, check that the apartment has the number of bedrooms and bathrooms that you need.
  • Space: typical size in square metres. The bigger the better obviously, but more space also means more costs and more maintenance (e.g. cleaning). Also, many apartments come with a basement compartment, providing additional storage for things you don’t use often.
  • Laundry: most apartments have a shared laundry room with one or more washing machines and tumble dryers. This is frankly a pain in the ass as you get a time slot and have to stick to it. So, ideally find an apartment which has its own waschturm, i.e. washing tower consisting of washing machine and tumble dryer.
  • Heating: underfloor heating is best, although other types are heating aren’t bad. See “Heating” for more about this.
  • Dishwasher: I think I’ve never seen a Swiss apartment that didn’t have a dishwasher, even older ones.
  • Position: there are different reasons to prefer being on the ground floor or a higher floor.
  • Lift: for apartments that aren’t near the ground floor, it’s better if the building has a lift.
  • Pets or musical instruments: most application forms ask specifically about these, so if you have any, you should check what the property rules are around them.
  • Telecommunications providers: usually you can choose any provider for internet, TV and telephony; however some apartments are locked with a specific one. Ask about this.
  • Location: there are a lot of aspects to this (see “City Life vs Countryside”), including:
    • Do you want to live in the city or in the countryside?
    • How far from the city are you willing to live?
    • Do you have all the amenities you need (e.g. supermarkets, schools, shops etc) nearby?
    • How far do you have to walk to the nearest public transport / Are you going to need a car?
    • Are you going to be too near to something noisy, such as a train station or a church?

As you can see, there are a lot of things to consider. Finding an apartment takes a lot of time and patience. As with a job, once you’ve been chosen for a particular apartment, you need to decide whether you want to take it. You might have just one option or else you might have multiple offers. Once you’ve accepted an apartment, though, companies usually take your word to be binding, and some will charge a fee if you change your mind (although the legal basis of this is very debatable).

Once you accept an apartment, you need to sign the contract and pay a deposit before you get the keys. The deposit varies, but most of the time it’s equal to three months’ rent (so if your monthly rent is 2,500 CHF, you need to pay a deposit of 7,500 CHF). You have two options to pay the deposit:

  1. Open a rental deposit account at a bank. This is a special account that both you and the property owner have access to. By “access” I really mean “visibility”, because neither can touch the money until something happens (e.g. you leave the apartment, or the owner sues you for damages). This is much safer than some countries where you give the owner a pile of cash and pray that someday you’ll get it back.
  2. Take an insurance that covers the deposit. It’s an extra expense but it is useful if you have limited liquidity – the rental deposit is, after all, a lot of money.

Liability Insurance

It’s common in Switzerland to get a liability insurance. While not required, this would cover any damage you do to third party property, e.g. the apartment you live in, or someone’s car. Because these expenses can be massive in Switzerland, and the insurance is quite cheap, it’s good to be covered.

Household Insurance

Again, not required, but it’s cheap to get insurance to cover your furniture and other things you have in your place. It’s a small price to pay for peace of mind.

Driving Licence

In most (if not all) European countries, your old driving licence is valid for only one year after moving to the new country, and if you want to keep driving in that country, you have to exchange your old driving licence for a local one. For some reason I’ve never understood, it is illegal to have more than one driving licence (from different countries).

Switzerland is no exception. So, if you plan to drive in Switzerland, you have to apply for a Swiss driving licence and surrender your old one within your first year. The process is quite simple:

  1. Go to the Kreisbüro/Gemeinde and get an application form.
  2. Go to an optician with the application form and do an eye test.
  3. Fill in the rest of the application form.
  4. Stick a passport-size photo to the application form.
  5. Return the application form to the Kreisbüro/Gemeinde.
  6. Receive your new Swiss driving licence by post within a couple of days.

It’s interesting that Swiss driving licences don’t seem to expire, so my understanding is that you don’t have to renew them every 10 years or so like in other countries. But, if you leave Switzerland, you would need to exchange the driving licence again and adhere to the rules of the new country.

Domestic Life

Living in a Swiss apartment is a little complicated. Every country has its own quirks, but let’s talk about the Swiss ones.

Furnishing

Most Swiss apartments are unfurnished. Typically, all you get is the structure, the kitchen, and the bathroom(s). You’ll have to get everything you need to live, including all the furniture, kitchenware, and usually even the lights. This is a big hassle in itself.

There are many companies you can go to for furniture, such as IKEA, Conforama, Micasa, and others. I don’t recommend IKEA even though they are the typical default go-to shop for most stuff, as they’ve given me a lot of hassle due to faulty products and mixed up deliveries. I don’t recommend Conforama either, as the one thing I bought (which cost a lot of money) broke in the first couple of weeks and again I had to chase them to fix it. All I can say is: shop around.

When you buy furniture and other things for your apartment, keep in mind:

  • Delivery charges: some companies charge a flat fee for the whole delivery, whereas others charge per item.
  • Assembly: labour is expensive in Switzerland, but it’s probably a lot less hassle to pay the company to set up the furniture than to do it yourself: it will save you time, injuries, and damage due to your own mistakes.

Kitchens

Swiss apartments come with kitchens included (unlike in Germany, or so I’m told). However, they tend to be relative small and have limited countertop space. Perhaps this is why microwaves aren’t really a thing in Switzerland – and neither are toasters, from what I’ve seen!

Internet and TV

Switzerland has very good infrastructure and you can have Gigabit internet even in the smaller villages. There are lots of options, so shop around depending on your needs. I recommend Swisscom as their service is great, but they are also quite pricey.

Heating

Swiss apartments are usually part of an apartment block (or “house”) and have shared facilities for heating. The heating is technically always on, and controlled in the apartment via thermostats. The thermostats have just a few notches so finding a comfortable setting is a matter of experimentation. It’s good practice to be energy-efficient and turn off the thermostats in rooms where you don’t spend a lot of time, and keep the rest on a low enough setting for you to be comfortable with the temperature.

Modern apartments tend to come with underfloor heating, which is excellent. In older apartments you’ll likely find radiator heaters fixed to the walls, which are not bad either.

Cooling

While Switzerland isn’t as warm as, for instance, Mediterranean countries, the summer can get warm enough to be uncomfortable (e.g. around 30 degrees Celsius). Since air conditioners aren’t a thing in Switzerland, it’s good to invest in a fan or two.

Ventilation

Unlike many other countries, apartments in Switzerland do not have air vents. Presumably this is to maximise energy efficiency by eliminating heat losses.

The insane aspect of this is that a lack of air circulation causes even bigger problems, such as stuffiness, mould and carbon dioxide poisoning. The advice from the health authorities is thus to fully open the windows (i.e. not on tilt) for 5-10 minutes 3 times a day. In a country where so many things are automated, having to do this manually raises eyebrows, for a number of reasons:

  1. Availability. A Swiss apartment is like having a cat: if you go on vacation, you have to find someone who can take care of it.
  2. Insects. Especially if you’re out all day and your only chance to ventilate is at night or when it’s dark.
  3. Privacy. Admittedly, people aren’t very nosy in Switzerland, but still.
  4. Loss of heat (the irony: isn’t this the problem this approach was supposed to solve?).
  5. Weather. What do we do when it’s raining all day every day for a week?

Waste Disposal

Switzerland is very organised when it comes to collecting all sorts of waste. This varies depending on the city/village you live in, so I can’t provide any general advice. But, just to give you a general idea based on my own experience:

  • Organic waste is collected separately in green bins outside. You can either keep your food, gardening etc waste in small compostable bags in your apartment and put them in the green bins regularly, or dump organic waste directly in the green bins.
  • General household waste is collected in bigger bins outside. Each city/village has their own special bags for this, so ask the local authorities or your apartment’s owner where to get them and where to dump them.
  • Most recyclable waste (e.g. beer cans, glass bottles or jars, wood, etc) can be brought to recycling plants and disposed of for free. Even smaller villages have these recycling plants.
  • More hazardous materials (e.g. batteries, light bulbs, electronics, etc.) are collected separately. Ask about the pick-up point for these in your locality.
  • Plastic deserves a longer discussion:
    • PET drinking bottles: all drinking bottles (as far as I can tell) are made from this plastic called PET, which is highly recyclable. You can typically return these to some supermarkets.
    • Other bottles: other bottles such as toiletries, cleaning products etc. can also be returned at some supermarkets, but in a slot separate from the PET drinking bottles.
    • Other recyclable plastic: the collection of any other plastic (including PET plastic that isn’t used for drinking bottles) varies depending on the locality.
    • Non-recyclable plastic: I think non-recyclable plastic (such as food packaging) goes in the household waste.

Sometimes it’s not clear what materials something is made from or whether it’s recyclable. Start by looking at the product’s packaging. Typically this will tell you whether it’s recyclable (two rotating arrows indicate recycling, vs a dark bag that indicates household waste) and where it goes (e.g. Karton means it goes with cardboard waste).

Keys

Typically, the key to your apartment also opens everything else, including your mailbox, the front door of your apartment building, the basement storage, and perhaps even the parking garage. Take good care of your keys as they may be very expensive to replace.

City Life vs Countryside

The great thing about Swiss cities is that they’re small. That means that it’s quite easy to live in the countryside and still be within 20-30 minutes from Zurich. It’s a great balance when compared to cities like London where you can commute for over an hour and still be in the city!

Swiss villages are very well-organised, even when they’re right in the middle of the countryside. Typically you’ll find almost everything you need, including:

  • Multiple supermarkets
  • A recycling plant
  • A fire department
  • Some shops
  • At least one school
  • Some sports facilities, possibly even a swimming pool
  • A train station
  • Nature all around
  • Great internet connectivity

On the other hand, Swiss villages are quite limited in terms of entertainment. So there might be a restaurant or two, but you won’t find a pub, a fast food take-away, or anything fun to do in the evening. This is not a big deal if you’re within a reasonable commute from Zurich, although it can add quite a bit to your transport costs if you go there regularly.

Whether to live in the city or the countryside is a subjective consideration that depends a lot on your needs, especially when it comes to social life, shops and other facilities.

However, property is a big part of this consideration. If you live in the city, you’ll likely pay more and get less space and an older building. In the villages, on the other hand, there are lots of recent real estate projects offering very high-quality, spacious accommodation at reasonable prices. So if you have a family and need more space, I’d recommend taking a look at property outside of (but near to) Zurich. Keep in mind though that transport is less frequent in the villages than in the city. If you miss a train, depending on where you live, you might be waiting for half an hour or more for the next one.

How Things Work

There are many things in Switzerland that take some getting used to, and apartments are only one of them. Let’s take a look at a few more.

Transport

Swiss transport is run by a lot of different companies, but the entire system is ultimately managed by SBB. The system is multi-modal and consists of trains of all shapes and sizes, buses, trams, ferries, and various mountain transport. You can buy tickets at the stations or get the SBB app, which is easier. As I mentioned before, I highly recommend getting the half fare pass which will save you a lot of money. This can be integrated in the SBB app, so every ticket you buy will automatically be charged at half the normal rate.

Trains are usually clean, spacious, energy-efficient and on time. However, they are also frightfully expensive, especially for tourists without the half fare pass. Just to give you an idea, a 7-stop (~10 minute) single trip from a village to the outskirts of Zurich cost me almost 7 CHF last year (without half fare), which in Vienna would just about get you a day ticket.

In Canton Zurich, the transport system is managed by ZVV and ticket fares are charged based on zones – you’ll need to see a zone map to figure these out.

  • When you buy a single ticket, it’s valid for 2 hours and you’re charged based on all the zones you pass through (including start and destination). Zurich and Winterthur (zones 110 and 120 respectively) cost double because they’re much bigger.
  • You can buy tickets in either 1st or 2nd class. Both are very comfortable so there’s little reason to go for 1st class.
  • If you want a return ticket, you go for the 24-hour ticket. You pay double, but you’re covered for 24 hours instead of 2, and you can come and go as much as you like within that period.
  • If you’ve already got a ticket and need to take a detour to some other zone, you can get an extension ticket to add zones.
  • As long as you are within the validity period, you can run around as much as you like within the zones you paid for.
  • The airport is very easily reachable by train and is just one zone away from central Zurich (2 stops from Zurich HB).
  • There are some General Availability tickets that give unlimited travel, but they’re so expensive that you need to travel a lot for them to be worthwhile.
  • Each community administration has a number of day tickets they can sell per day at a flat rate (price and number of tickets varies per community), so these might be worthwhile for longer trips; be sure to ask them.
  • Some Swiss cantons offer free public transport within the canton when you stay at a hotel there.
  • The system operates on a trust basis and there are no barriers requiring tickets. However, there are lots of random checks and hefty fines for abuse. If you use the SBB app, you can show the ticket’s QR code from either the app itself or the email confirmation to the inspector.
  • Some areas outside of Canton Zurich (e.g. Rapperswil-Jona) are still part of the same system and the same rules apply.

At bigger train stations, the displays will usually show the configuration of the train (i.e. where the 1st and 2nd class cabins are) and where on the platform it will arrive. For instance, a platform at the Zurich HB (central station) might have letters from A-F, but a smaller train might stop at letters B-D, so you don’t want to be waiting at letter F when the train arrives. Also, listen carefully to any service announcements about disruptions, delays, or replacement buses (unfortunately, these are in German only).

Transport in the Zurich region is hub-and-spoke, with most routes passing through the massive Zurich HB, and many also going through the satellite stations Hardbrücke or Stadelhofen depending on direction. The system is generally efficient, but if you live out of town, it might take a while to go somewhere because you’d have to take a connection at Zurich HB, even if your destination is relatively close to where you are. This is less optimal than, for instance, Vienna’s spiral metro system, but you can’t compare a regional transport network to that of a city.

Trips outside of Canton Zurich (e.g. going to Lucerne) use point-to-point tickets, so the rules and validity are a little different.

Healthcare

I honestly don’t know that much about the healthcare system, but it’s basically all private healthcare and that’s why you have to have a health insurance. Everyone is required to have a health insurance by law (set up within the first 3 months of arrival), and insurance companies can’t refuse to insure you (e.g. due to pre-existing conditions), as that would violate your basic right to healthcare.

The system is quite expensive. A basic health insurance cover typically costs around 300 CHF per month, and you can also pay extra for things like private wards in hospitals or better travel cover. However, health insurances usually have what is called a deductible, e.g. 2,500 CHF. That means that when you claim your medical expenses, the health insurance doesn’t actually pay you anything until you go over those 2,500 CHF.

It’s kind of a bad deal if you’re healthy because you’re paying a lot of money monthly for the privilege of… not getting paid anything (the risk is on you). But, having such a high deductible is necessary to keep the premium relatively low. On the other hand someone who has frequent medical commitments would benefit from paying a higher premium and having a lower deductible so that more medical costs would be covered.

The system to see a doctor depends on what health insurance product you chose. Typically when you see a doctor, you give the clinic your health insurance details, and you don’t pay anything. The clinic charges the health insurance directly for both the visit to the doctor and any medicines, and I suppose you somehow get forwarded that cost.

You can buy certain over-the-counter medicine directly from a pharmacy, but it typically costs at least double what it costs in other countries. So if you visit your home country at least once a year, it’s good to bring a stash of common things like headache medicine with you.

Taxation

In Switzerland, you’re generally taxed at source on your employment income at 3 levels which match the government/administration hierarchy: municipal, cantonal and federal. These taxes vary depending on where you live, and in Canton Zurich they’re among the lowest (typically all together not exceeding about 25%).

Contributions to a third-pillar pension account (see “Pension” below) are tax-deductible so it’s worth maxing this out in order to get a decent reduction on your tax bill.

There is a special radio tax that you have to pay once a year. It costs something over 300 CHF and you’ll receive a notification by post, which can be quite a fright if you didn’t know about it.

Switzerland, like its German-speaking neighbours Austria and Germany, has church taxes. This means that you pay extra tax depending on your religion. So it literally pays to avoid mentioning your religion on any official form that asks about it.

There’s also a wealth tax you have to pay that is a percentage of your total wealth.

I’m told that if you earn less than 120,000 CHF per year, you probably don’t need to file a tax return at all (assuming your income is taxed at source and you don’t have other income streams to declare).

I don’t know too much about the tax system in general, so if you’re new to the country, your best bet is to engage the services of a professional tax accountant. They can take care of filling in your tax return and also help optimise your tax (e.g. by claiming deductions and expenses you might not know about). Their fees vary wildly, and some of those you’ll find easily on the internet charge exorbitant amounts of money. So ideally, ask some friends or colleagues and find a reasonably priced one through word of mouth.

Pension

The Swiss pension system is based on 3 pillars:

  1. State pension (you get this from the government)
  2. Work pension (you contribute towards this via deductions from your income)
  3. Third pillar pension (you optionally contribute towards this)

The pension amounts of the first two (compulsory) pillars are barely enough to pay rent and living expenses, so it’s important to supplement them with a third pillar.

The third pillar is optional and can be a combination of a special savings account as well as investment funds, which are capped at a certain amount per year (e.g. CHF 6,883 in 2022). It’s worth investing in a third pillar because:

  • It gives you more financial security in the long term if you plan to retire in Switzerland.
  • It decreases the amount of tax you have to pay.
  • Although you can’t normally touch the funds you put into the third pillar, you can take them out in special circumstances (e.g. retirement, leaving Switzerland, or getting a home loan).

Post

Although many services are digital in Switzerland, there are still a lot of things that are sent by post, such as official notifications or bills.

The postal service is very efficient and if you want something to arrive quickly (e.g. within one working day, or sometimes even same-day), pay a little extra for “Priority A” delivery.

In Switzerland, mail is delivered to a named address, not just to a house/apartment number. This means that even if the address is correct, the mail will not be delivered unless someone’s name is on a mailbox in that building.

Paying Bills

Many services (e.g. rent, health insurance, internet & TV) are paid via QR bills. The company sends you a bill via email, their online portal, or post. You scan the QR code with your bank’s mobile app and confirm. It’s very easy. The QR code contains all the information required for the bank transfer.

Debt Enforcement

I’m happy that I don’t know much about this topic. Apparently if you don’t pay your bills, you get in trouble with the debt enforcement register… I’ve heard of policemen knocking at your door, fines and such. Remember also that having a clean record is required for certain things like applying for apartments. So, always pay your bills on time.

Real Problems

Life in Switzerland has a lot of advantages. These are discussed ad nauseam on other websites. Here, I’d like to talk about practical problems that people might either not know about or be underestimating.

Cost of Living

It’s well-known that the cost of living in Switzerland is very high. This in itself is not a problem, because the high salaries and low tax mean you can still save a lot of money. Just to give a simple example: imagine you earn 120k CHF in an IT job. Deduct 30k in tax (assuming it’s 25%) and another 30k in rent (assuming 2,500 CHF per month for 12 months). That leaves you with 60k CHF in disposable income, which is much more than you could get in most other countries even considering the high cost of living.

However, the costs do add up if you’re not careful. ~10 CHF each train trip over 5 zones, 30 CHF to change a watch battery, 46 CHF for a nasal spray from the pharmacy… if you think about it, when a meal at a restaurant costs some 50 CHF, two or three meals add up to the cost of a flight. So, although you can live comfortably in Switzerland, do some basic budgeting and keep track of your expenses to avoid nasty surprises.

I find the disproportionate cost of some things to be quite annoying, to be honest. Usually this is explained as either (a) everyone including the waiter has a good salary so that’s reflected in the prices, or (b) well that restaurant on the mountain, it cost a lot to get it up there, so you have to pay more. There’s also the idea of certain Swiss things (e.g. knives, watches, etc) being special – a bit like Irish beef or Italian salami. I find this to be like buying Apple products – you’re paying mainly for the prestige of the brand. I frankly don’t care that the sausage is Swiss or that I’m having it on a mountain – 30 CHF for a sausage is still ridiculous!

Buying Property

Most people in Switzerland rent apartments. Buying an apartment is so expensive that it’s out of reach for most people, with typical prices in excess of 1 million CHF, not including the costs associated with the purchase. The Poor Swiss has two very good articles on the topic (“Should you buy or rent a house in Switzerland?” and “Buying a house in Switzerland: The Complete Guide“) so I won’t go into detail on this topic, but there are a couple of aspects I’d like to mention.

The first of these is the lesser-known “imputed rental value” tax. Although people usually buy property to stop paying rent, that’s not quite the case in Switzerland. Because even when you own a property and live in it, you have to pay tax based on the theoretical income you would earn if you were to rent it out (which is basically a huge scam). I might be wrong, but my understanding of this is: if you could rent out your property at 2,000 CHF a month, assuming your income tax rate is 25%, then you have to pay the government 500 CHF a month on the property you’re living in.

The second is having to maintain the property. When you rent, it’s kind of “property as a service”: you have most things taken care of and you can reach out to the owner or management company if there are problems. When you own your place and you have problems, you have to do the chasing and foot the bills yourself. That’s especially difficult to do if you don’t speak the local language.

Language Barrier

Switzerland has four official languages: German, French, Italian, and Romansh. Each canton has one or more official languages, with German holding the majority. However, government services and larger private companies will typically converse in any of German, French or Italian regardless of which canton they’re in (I suppose Romansh is too much of a minority language except in its home canton).

Coming from an English-speaking country, I found it very surprising that most people seem to either not know or not want to speak English, despite the high number of expats. This makes it very hard to obtain goods, services or help and the language barrier should not be underestimated. While government services and bigger companies usually have people that speak English, it’s good to know at least one of the official languages as a fallback. For instance, if you live in the German part, you can sometimes use Italian when they don’t speak English.

So why don’t they speak English, which is so ubiquitous? If you lose your English-speaking bias for a moment and think about it from their perspective, you’ll realise that:

  • This is the German-speaking world, not the English-speaking world. You wouldn’t go to China and expect them to speak to you in English.
  • They already have enough languages they have to learn and be fluent with.
  • You’re the guest. You need to adapt to their way of life, not vice versa.

It’s also worth noting that Swiss German is quite different from normal (“High”) German. So even if you know a little German, chances are you won’t understand anything the locals say. To make matters worse, Swiss German is a spoken-only language, and written communications are always in High German.

The Google Translate mobile app is a life-saver if you don’t understand the language. It’s much more useful to the simple web translator we’re used to: with the app, you can literally point your smartphone’s camera at a letter, food menu or other text and it will overlay the translation in real-time – one of the few truly useful applications of augmented reality I’ve ever seen. Unfortunately, it still can’t help you decipher automated answer machines in German though!

Communication

My impression of Switzerland is that they’re really good at building things and making them work efficiently, but not at communicating how they work. I feel that there’s always the assumption that people are born knowing how things work (“common sense” perhaps), and nobody tells you anything unless you run into a problem and have to ask. I find that reactive rather than proactive.

As a result, some things can be really confusing, such as:

  • Signs – navigating the labyrinthine Zurich HB, getting around the airport, or locating the Welcome Desk
  • Space toilets
  • No train company employee presence at all in most train stations except major hubs such as Zurich HB or the airport.
  • Everything I wrote about in this article. I wouldn’t have had to write it if the information was readily available.

Isolation

Switzerland is in some ways a victim of its own success. As a rich country, it hasn’t joined the EU, retains its own currency, has its own variant of German, and is not part of the EU Zone 1 mobile network. As a result, living in Switzerland means that travel to EU countries is less easy than between EU countries – although there’s nothing to stop you (due to existing agreements between countries), you have to deal with a lot of these differences every time.

Some Swiss companies will completely avoid doing business with any country outside of their immediate neighbours. This might be a matter of language or risk. The earliest example I’ve seen of this is Galaxus, Switzerland’s biggest e-commerce website, accepting credit cards only from a small set of countries:

“”For security reasons, the credit card you specified cannot be used. We only accept credit cards from the following countries: Switzerland, Liechtenstein, Austria, France, Germany, Italy and United Kingdom.””

— Galaxus error message when paying with a foreign credit card

Jobs

Although I’m not very familiar with the Swiss job market, it seems like most IT jobs tend to be with traditional companies like banks, insurances or telecommunications providers. If you’ve worked in IT for a while, you’ll probably recognise that these are the sort of companies for whom IT is an expense rather than an enabler, and who do less innovative work, and who are more likely to be running in a command-and-control fashion.

However, Switzerland does have its share of Big Tech (e.g. Google has a huge presence, especially in central Zurich) and startups, so I’m not saying that the prospects are dull. Just keep in mind that it’s a relatively small market, so the options are more limited compared to a bigger country like Germany.

Keep in mind that in general (not just in IT), Zurich is the financial capital of Switzerland, so it is a business hub and most jobs are in this region. Thus, it’s worth being close to Zurich even if you work remotely or can find a job elsewhere. You may have to find a new job someday.

Myths

There are a lot of things we’ve heard about Switzerland in the past. Some of them are true, and others not so much. Let’s talk about the latter.

Everything Works

“Swiss trains are always punctual”, they say. I’ve seen my fair share of late Swiss trains, and they were the least of my problems. Without going into the details, I’ve paid a lot of money for a lot of things that didn’t work in Switzerland. Some problems are very expensive to fix. So, forget the hype and get ready to deal with issues just like in any other country.

Noise

I like the peace and quiet of the Swiss countryside. Part of what makes that work is that people are considerate and try not to make excessive noise, especially at sensitive hours such as at night.

However, nobody expects this to be taken to an extreme, as some urban myths claim that you’re not allowed to flush the toilet at night. In fact, many sounds such as running a bathroom extractor/ventilator or the dishwasher aren’t even audible from neighbouring apartments. Using your tumble dryer at 4am, on the other hand, might not be appreciated by your neighbour who needs to get up at 6am.

Generally, it’s a matter of being considerate and not causing disturbances to other people. While people do sometimes call the police in situations of excessive noise, they would normally talk to you directly first. Also, sometimes it’s a matter of two weights and two measures. In my village, nobody has any problem with the church bells ringing every 15 minutes, day and night!

Long-Term Considerations

So you’ve moved to Switzerland and got your things sorted. What next? Maybe you decide to stay in Switzerland, or maybe not. While there’s plenty of time to plan ahead, some things (e.g. learning German) do take a while, so it’s best not to leave them until the last minute.

Getting the C Permit

Assuming you’re an EU citizen and have the B permit, you’re technically a temporary resident for 5 years, although your permit can be renewed.

The next step up is to become a permanent resident. That’s the C permit. As a B-permit holder, you can get the C-permit after 5 or 10 years with varying requirements of German fluency. You can get the most up-to-date official details from the Welcome Desk. I’ve just been to visit them in person a couple of weeks ago, so here are some of the conditions valid at the time of writing this:

  • After 5 years:
    • No German requirements at all if you come from a list of countries that includes France, Germany and Austria among others.
    • With a level of B1 spoken and A1 written German otherwise.
  • After 10 years: With a level of A2 spoken and A1 written German otherwise.

As you can see, the language requirements are pretty basic so there’s nothing to worry about. You can do a little learning at your own pace with Duolingo, find a private tutor, or take a course. The Welcome Desk is very helpful at helping you locate the right course for you (based on criteria such as location, frequency, and price).

When it’s time to get your C permit, take a recognised German exam to prove your level, and take the result to the Kreisbüro/Gemeinde as part of your application.

Swiss Citizenship

I don’t know much about this, but if you’re really serious about Switzerland, the next step up from the C permit is to become a Swiss citizen. This presumably has more complex requirements than the C permit… I don’t know exactly what they are and don’t want to repeat hearsay without having any official information at hand.

However, this is not really required, and only has a few advantages (e.g. being able to vote).

Moving to a New Home

If you want to move to a new apartment for whatever reason, get ready for a big hassle.

  1. You’ve seen in “Finding an Apartment” how complex it is to secure a new apartment. You’ll have to go through that again.
  2. You need to give your current property manager enough notice as per your rental contract (e.g. 3 months).
  3. Even so, you’ll only be able to leave at one of the official moving dates, i.e. end of March, end of June or end of September.
  4. You’ll need to move all your furniture and other stuff. You can either do this yourself (and die trying), or pay a lot of money to a moving company that will take care of everything including dis/assembly of furniture, actual moving, and professional cleaning.
  5. Before you leave, you need to pay for professional cleaning of the apartment. A moving company may be able to handle this for you.

Leaving Switzerland

If Switzerland is not working for you, you have every right to leave. Before you do that though, you’ll need to close off your commitments, e.g. your rental agreement, bank account, internet provider, etc. Most companies are happy to terminate a contract early at no cost if you can prove that you are leaving Switzerland, although your rental agreement doesn’t fall in that category. The only way you can leave your apartment early is if you find a suitable tenant to replace you and that tenant is approved by the landlord.

Some readers pointed out that when you permanently leave Switzerland, you can cash out not only your third pillar pension savings, but also your second pillar under some circumstances. Generally, your second pillar remains in Switzerland in a special account until you retire, but you can cash out a small portion of it when you leave the country. See “Moving to-do list: Things to consider before leaving Switzerland” for a concise summary of what happens to each pillar when you leave.

When you have finally sorted everything out and you’re ready to leave, you have to deregister from the administration of the community you’re living in. You will need to give back your residence permit, and possibly also provide the details of your tax representative who will sort out any outstanding tax obligations on your behalf.

GoLang Timestamps: A Cross-Platform Nightmare

Have you ever had one of those bugs where your tests failed in your Continuous Integration (CI) pipeline, but they worked just fine locally, and the only way to troubleshoot the problem was to add logs and wait significant amounts of time for each run to fail? Well, I had one of those this week, and I learned a thing or two in the process. I’m hoping to share that here for anyone else who might run into the same problem.

Time Precision Across Operating Systems

Let’s create a really simple Go program.

  1. Create a new folder.
  2. In that folder, run go mod init main
  3. Create a file called main.go and paste the following code:
package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now())
}

Nothing special, right? It just prints out the current time. Let’s run it then.

The following is the output on my personal laptop running Linux:

$ go run main.go
2022-10-27 17:34:43.471537065 +0200 CEST m=+0.000016185

And the following is the output on my work machine, which is a Mac:

$ go run main.go
2022-10-27 17:35:27.349114 +0200 CEST m=+0.000181459

See the difference? The Linux output was precise to the nanosecond (9 fractional digits of a second), whereas the Mac output was precise to the microsecond (6 fractional digits of a second). This subtle difference was the root cause of my problem.

How Did It Happen?

I had written automated tests to verify some simple CRUD functionality. I would send the data to an API, and the API would store it in a PostgreSQL database. Then, I would retrieve the data and verify that it matched what I had sent. Sounds trivial? Yes, but it failed. It failed on the CI server where I couldn’t debug the problem as easily as I could on my machine.

The reason it worked on my Mac was that a timestamp field in PostgreSQL has microsecond precision. Coincidentally, that’s the same precision that I get for Go time on my Mac.

However, on the CI system as well as on a colleague’s WSL system, things worked differently:

  1. The test data, as well as the expected values to be compared later, are generated in Go. Timestamps have nanosecond precision.
  2. The data is sent via the API and stored in the database. There’s a loss of precision and the timestamps are stored with microsecond precision.
  3. The test retrieves, via the API, the same data that has just been saved. The timestamps come back with microsecond precision.
  4. The automated test compares the expected values (nanosecond precision) with the actual values (microsecond precision) and finds that they are different. The test fails.

How Did I Resolve It?

Honestly, I don’t know what the right way to solve this problem is. It’s a pretty messy situation reminiscent of floating-point error, and that in fact influenced my solution.

The first thing I did was strip off the extra precision. Go time has this Truncate() function you can use for exactly this reason. For instance, let’s try the following:

func main() {
	fmt.Println(time.Now())
	fmt.Println(time.Now().Truncate(time.Microsecond))
}

The output on my Linux laptop then looks like:

$ go run main.go
2022-10-27 19:06:52.427287572 +0200 CEST m=+0.000013810
2022-10-27 19:06:52.427347 +0200 CEST

Doing this on my Mac would, I suppose, mean that the Truncate() is a no-op and just returns the same thing – at least that’s the behaviour I observed when testing it out.

However, in practice, Truncate() alone didn’t solve the problem. Some tests kept failing intermittently because the last digit (the microsecond) was off by one. I’m not sure what was causing this – perhaps some kind of rounding, e.g. when the data goes into the database.

So I used the same approach as with floating-point equality comparisons and decided to allow an error of one microsecond, i.e. if two timestamps are one microsecond apart, we assume they’re still equal. This is as simple as using Sub() to calculate the interval between two timestamps, and consider them equal if it’s not greater than one microsecond:

func timestampsEqual(a, b time.Time) bool {
	return b.Sub(a) <= time.Microsecond
}

Let’s test it out with some code:

func main() {
	t1 := time.Now().Truncate(time.Microsecond)
	t2 := t1.Add(time.Microsecond)
	t3 := t2.Add(time.Microsecond)

	fmt.Println("t1 == t2: ", timestampsEqual(t1, t2))
	fmt.Println("t1 == t3: ", timestampsEqual(t1, t3))
}

And the output would be:

$ go run main.go
t1 == t2:  true
t1 == t3:  false

So, it’s not great, and I’m sure there are ways to improve, but it seems to have solved my problem at least. One thing I’d like to do is to use some equivalent of math.abs() so that the order of the timestamps doesn’t matter. But, I have no idea how to do that with Go time with out-of-the-box functionality.

The Eighth Anniversary

One year ago today, on The Seventh Anniversary, I announced my retirement from tech blogging:

“However, at the same time, life circumstances have changed quite a bit, and my interest in free-time coding and writing has been waning. As a result, for the time being, I am retiring from tech blogging. It’s quite possible that I might write something interesting from time to time, but for now, let’s say I’m taking a break.”

Despite that, I managed to write five articles over the past year:

The first four are things I have been working with, whereas the last one is something from my MSc days that I’ve been wanting to write for a decade.

As I now celebrate the 8th anniversary of this blog, writing a handful of articles in a year doesn’t bother me at all. In fact, on The Sixth Anniversary I made the commitment to focus on quality rather than quantity. Having recently changed tech stack completely, I’ve been inspired to write about some things that I felt were both interesting and poorly documented, despite my apparent retirement from tech blogging.

And this is how it will continue to be: I’ll write something if and when I think it is useful to do so.

Calculating Circle Area the Monte Carlo Way

Ten years ago, I was in the middle of my MSc degree, titled “Distributed High-Fidelity Graphics Using P2P”. My research revolved around ray tracing – a family of techniques used to produce highly photorealistic images by simulating various aspects of Physics, especially the way light interacts with the various surfaces and materials it comes in contact with.

Ray tracing is very complex and computationally intensive, and it would take an entire book to write anything substantial about it. But, at the heart of modern ray tracing is an approach called Monte Carlo simulation, or stochastic simulation. It’s a fancy way of saying: this problem is too complex and I don’t have an easy way to calculate a solution, so I’ll take a number of random samples and approximate it instead.

In this article, I’ll illustrate the concept by calculating the area of a circle. Since we have an easy formula to calculate the area of a circle (πr2), there’s normally no need to do this via Monte Carlo simulation. However, it’s an easy way to explain the concept, which you can then use to solve more complex problems.

Approximating the Area of a Circle in Theory

Let’s assume that we don’t know how to calculate the area of a circle – either because a formula does not exist, or because it is too complex to derive.

However, we do have a way to determine whether a point lies inside a circle. If the point is represented by the coordinates (x, y), then the point lies inside the circle of radius r if (x2 + y2) <= r2, assuming that the circle’s centre is located at (0, 0).

A visualisation of a Monte Carlo approximation of a circle.

In this case, we can take a number of random points in space and compare how many fall inside and outside of the circle. You can see a simple visualisation of this above. Imagine we were throwing darts at a dartboard while blindfolded. The more darts we throw, the more we are filling in the circle, and the ratio of darts inside vs outside the dartboard tells us the overall area we covered.

It’s a little counterintuitive to imagine how a random process leads towards a deterministic solution. In fact, it’s not really deterministic, and the actual result changes with every run; but the approximation does work very well, and the more samples you take, the closer you get to the real solution. Let’s test this out in practice.

Approximating the Area of a Circle in Python 3.8

The code to implement the Monte Carlo approximation of the area of a circle is quite straightforward, as you can see below.

import random

def get_random_coord(radius):
    return random.uniform(-radius, radius)

def calculate_area_monte_carlo(radius):

    total_in_circle = 0

    for i in range(0, 10000000):
        (x, y) = get_random_coord(radius), get_random_coord(radius)
        in_circle = x ** 2 + y ** 2 <= radius ** 2
        
        if in_circle:
            total_in_circle += 1

        if i in [9999, 99999, 150000, 999999, 1500000, 9999999]:
            approximate_area = (2 * radius) ** 2 * total_in_circle / i
            print(f"Area ({i} samples): {approximate_area}")

Essentially, all I’m doing is:

  • Defining a helper function get_random_coord() to generate a random coordinate, just so that I don’t have to repeat the same code twice.
  • Generating an (x, y) coordinate pair within the square containing the circle.
  • Determining whether this (x, y) falls within the circle, using the aforementioned formula (x2 + y2) <= r2, in which case I increment total_in_circle.
  • At specific (arbitrary) intervals (numbers of samples), I calculate the approximate area of the circle and print it out to show how the calculated area gets more accurate, the more samples you take.

The approximate area is calculated as a ratio of samples in circle (total_in_circle) vs total samples both inside and outside of the circle (i). However, we have to adjust that by the area of a square, which is 2r2, as explained in this Stack Overflow answer.

In reality, we do know a formula to accurately calculate the area of a circle (πr2), so let’s toss that in as well in order to compare how accurate the results are:

import random
import math

def get_random_coord(radius):
    return random.uniform(-radius, radius)

def calculate_area_monte_carlo(radius):

    total_in_circle = 0

    for i in range(0, 10000000):
        (x, y) = get_random_coord(radius), get_random_coord(radius)
        in_circle = x ** 2 + y ** 2 <= radius ** 2
        
        if in_circle:
            total_in_circle += 1

        if i in [9999, 99999, 150000, 999999, 1500000, 9999999]:
            approximate_area = (2 * radius) ** 2 * total_in_circle / i
            print(f"Area ({i} samples): {approximate_area}")

def calculate_area_formula(radius):
    area = math.pi * radius ** 2
    print("Area (reference):", area)

def main():
    radius = 400
    calculate_area_monte_carlo(radius)
    calculate_area_formula(radius)

if __name__ == "__main__":
    main()

We can now run this program, and after a little patience, we get some results:

$ python3 main2.py
Area (9999 samples): 501874.1874187419
Area (99999 samples): 503793.8379383794
Area (150000 samples): 503940.26666666666
Area (999999 samples): 502511.2225112225
Area (1500000 samples): 502637.2266666667
Area (9999999 samples): 502743.410274341
Area (reference): 502654.8245743669

If we run it again, the results are a little different, but the trend is still there:

$ python3 main2.py
Area (9999 samples): 506930.69306930696
Area (99999 samples): 501861.0186101861
Area (150000 samples): 502101.3333333333
Area (999999 samples): 502941.30294130294
Area (1500000 samples): 502856.1066666667
Area (9999999 samples): 502779.44227794424
Area (reference): 502654.8245743669

This is the essence of the Monte Carlo approach: the more random samples you take, the more you’re filling in the problem space. However, this comes at a cost: the more samples you take, the more time it takes to compute. With enough samples, the error eventually becomes small enough that the approximation is indistinguishable from an accurate solution. Let’s visualise this.

Visualising the Area of a Circle Approximation

We can use the PIL library to quickly generate progressive images of the circle coverage. All we need is to add a few lines to our existing code:

import random
import math
from PIL import Image

def get_random_coord(radius):
    return random.uniform(-radius, radius)

def calculate_area_monte_carlo(radius):
    diameter = radius * 2
    image = Image.new("RGB", (diameter, diameter), (255, 255, 255))
    in_colour = (255, 0, 0) # red
    out_colour = (0, 0, 255) # blue

    total_in_circle = 0

    for i in range(0, 10000000):
        (x, y) = get_random_coord(radius), get_random_coord(radius)
        in_circle = x ** 2 + y ** 2 <= radius ** 2
        
        if in_circle:
            total_in_circle += 1
            colour = in_colour
        else:
            colour = out_colour

        image.putpixel((math.floor(x + radius), math.floor(y + radius)), colour)

        if i in [9999, 99999, 150000, 999999, 1500000, 9999999]:
            approximate_area = (2 * radius) ** 2 * total_in_circle / i
            print(f"Area ({i} samples): {approximate_area}")
            image.save(f'circle_{i}.png')

def calculate_area_formula(radius):
    area = math.pi * radius ** 2
    print("Area (reference):", area)

def main():
    radius = 400
    calculate_area_monte_carlo(radius)
    calculate_area_formula(radius)

if __name__ == "__main__":
    main()

What we’re doing here is:

  • Creating an image at the beginning.
  • For each sample, we colour the corresponding pixel either red (if it’s in the circle) or blue (if it’s outside the circle). Note that we have to add the radius to x and y because in the image, (0, 0) is not the centre of the circle, but the upper-left corner of the image.
  • Saving an image whenever we print an approximate area.

Earlier, we saw how the numbers seemed to be converging towards the accurate solution. If we now run the updated code above, we can verify the progressive coverage of the circle from actual images (click to enlarge):

Applications

As I said earlier, the Monte Carlo approach is not necessary for problems where we have a simple formula, like calculating the area of a circle. However, not all problems have a simple formula.

If you’ve studied calculus, you’ll know that you can integrate a function to calculate the area under its graph. You can do that for a simple function like 5x2, but there are more complex functions for which it is impossible to derive an analytical solution. Even if you never studied calculus, you can imagine how hard it must be to calculate the area of an irregular shape, such as your favourite politician. Randomly throwing darts at them and counting how many hit might be one way of working that out.

And if you ever work with ray tracing, you’ll eventually realise that ray tracing is really just another integration problem – one where you have to calculate the area (or contribution of light towards a surface) of something very irregular. A Monte Carlo approximation is a very effective – if computationally expensive – way of solving this otherwise intractable problem.