Battle Simulation With Lanchester Model in C#


This post will show a simple implementation of the famous Lanchester equations to simulate battles “evolution”.

For those that does not know this model, i really recomend this and this PDFs. (especially the first one). For the rest of the post, iam assuming that the reader “WILL read” these recomended texts =P.

Lanchester modeling is pretty beautiful cause it is based in very simple hypothesis and even so, it stills very usefull. (not so good as some stochastic models but good enough for lots of situations ).

In simple ways, we have a system of Differential equations to solve. There are LOOOTS of numeric methods avaliable, i choose one that for me is very intuitive and easy to implement. (using EigenValues and Eigen Vectors -> it is graphically intuitive =P)

The following code shows the Lanchester Model Implementation:
I used plain C# with .net and the alglib for math.
Actually, the alglib was used just to get the eigenvalues and eigenvectors of the lanchester diferential system. It could be easily done by “hand”. (calculate roots of the characteristic equation to find the eigenvalues and then substitute in the formal eigenvector/eigenvalue definition equation to get the eigenvectors =P).

The Squad Class (represents one Army =P)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Settlers.Battle
{
    class Squad
    {
        public float numericalStrenght;
        public float effectiveness;
    }
}

The simulator class:

There are some static methods that can be used to discover the winner before the “Battle begin =P” (without explicitelly using the time variable. See the recomended papers to know the reason why we can do this)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Settlers.Battle
{
    class LanchesterSimulation
    {
        public LanchesterSimulation(Squad a1, Squad a2)
        {
            double[,] vects = new double[2,2];
            vects[0, 1] = -a2.effectiveness;
            vects[1, 0] = -a1.effectiveness;
            double[] real = new double[2];
            double[] ima = new double[2];
            double[,] left = new double[2, 2];
            double[,] right= new double[2, 2];

            alglib.rmatrixevd(vects, 2, 2, out real, out ima, out right, out left);

            ev1 = real[0];
            ev2 = real[1];

            auv1x = right[1, 0];
            auv1y = right[0, 0];

            auv2x = right[1, 1];
            auv2y = right[0, 1];

            c2 = (a2.numericalStrenght - (a1.numericalStrenght * auv1y) / auv1x ) * auv1x / (-auv2x * auv1y + auv2y * auv1x);
            c1 = (a1.numericalStrenght - auv2x * c2) / auv1x;

        }

        double ev1, ev2;
        double c2, c1;
        double auv1x,auv1y,auv2x,auv2y ;

        public float GetArmy1Size(float t)
        {
            double resp = c1 * auv1x * Math.Exp(ev1 * t) + c2 * auv2x * Math.Exp(ev2 * t);
            return (float)resp;
        }

        public float GetArmy2Size(float t)
        {
            double resp = c1 * auv1y * Math.Exp(ev1 * t) + c2 * auv2y * Math.Exp(ev2 * t);
            return (float)resp;
        }

        public static Squad WhoWillWin(Squad a1, Squad a2)
        {
            float val = a1.effectiveness * a1.numericalStrenght * a1.numericalStrenght - a2.effectiveness * a2.numericalStrenght * a2.numericalStrenght;
            return val > 0 ? a1 : a2;
        }

        public static Squad[] WhoWillWin(Squad[] a1, Squad[] a2)
        {
            float apower = 0;
            float atotal = 0;
            for (int i = 0; i < a1.Count(); i++)
            {
                apower += a1[i].effectiveness * a1[i].numericalStrenght;
                atotal += a1[i].numericalStrenght;
            }

            float bpower = 0;
            float btotal = 0;
            for (int i = 0; i < a2.Count(); i++)
            {
                bpower += a2[i].effectiveness * a2[i].numericalStrenght;
                btotal += a2[i].numericalStrenght;
            }

            float val = apower * atotal - bpower * btotal;
            return val > 0 ? a1 : a2;
        }
    }

}

That is all for today =P

  1. #1 by relationships on 26 de fevereiro de 2017 - 6:23 pm

    As I site possessor I believe the content material here is rattling wonderful , appreciate it for your hard work. You should keep it up forever! Good Luck.

  2. #2 by moncler outlet usa on 26 de fevereiro de 2017 - 7:32 pm

    Personally Im impressed by the quality of this. Generally when I come across these sort of things I like to post them on Digg. I dont think this would be the best to submit though. Ill look around and find another article that may work.
    moncler outlet usa http://www.cheapmoncler.online

  3. #3 by casette da giardino on 26 de fevereiro de 2017 - 7:34 pm

    WONDERFUL Post.thanks for share..extra wait .. …

  4. #4 by http://myfreecoins.top/free-coins-on-fifa-14-ultimate-team.html on 27 de fevereiro de 2017 - 12:36 am

    Big help, big help. And superlative news of course.

  5. #5 by box auto legno on 27 de fevereiro de 2017 - 2:42 am

    I got good info from your blog

  6. #6 by cassette in legno on 27 de fevereiro de 2017 - 2:42 am

    Valuable information. Lucky me I found your website by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.

  7. #7 by info on 27 de fevereiro de 2017 - 3:01 am

    I got what you intend,saved to bookmarks, very decent site.

  8. #8 by http://accessfreecoins.pro/subway-surfers-hack-for-ios.html on 27 de fevereiro de 2017 - 3:01 am

    Thanks for the feedback Paul. BTW: I love the term your niece uses; “considered openness”.I have variously been told that between 80% and 95% of people check out a potential service provider online, before hiring their services. I can see this number increasing, if anything.

  9. #9 by link on 27 de fevereiro de 2017 - 3:09 am

    Very interesting points you have remarked, thanks for posting. “Without courage, wisdom bears no fruit.” by Baltasar Gracian.

  10. #10 by patagonia online on 27 de fevereiro de 2017 - 3:57 am

    This website is awesome. I constantly come across something new & different right here. Thank you for that data.
    patagonia online http://www.mcadamssupplyco.com/patagonia/

  11. #11 by pierre hardy pouch on 27 de fevereiro de 2017 - 5:39 am

    Great! Thanks for post.|ipod touch 32gb 3rd generation|ipod touch best price 16gb|le creuset recipes|best shampoo for men |baci chocolate |heart shaped diamond rings|casio keyboard manual |casio compass watch |casioz25 |organic tampons |osis hair products |pert shampoo |Canon Powershot Sd1400is Reviews|Canon Powershot Sd1400is Review |refurbished ipodtouch review|8g ipod touch|ipod touch reviews 8gb|ipodtouch 4g release date|ipod touch fm trans mitter review
    pierre hardy pouch http://www.pierrehardystore.online

  12. #12 by http://gamegoldfree.top/panda-pop-hack-for-android-no-survey-no-download.html on 27 de fevereiro de 2017 - 6:39 am

    Welcome home indeed! Praying God blesses you rest and recovery, with much rest. Praying!! Your faith is an inspiration. May you one day know the amazing impact you have had on us all. We are the blessed ones by you letting us in. Thank you and hooray!!!

  13. #13 by tinder dating site free on 27 de fevereiro de 2017 - 6:53 am

    Wow, this paragraph is good, my sister is analyzing such
    things, so I am going to tell her.

  14. #14 by Yeezy Boost 350 Deutschland Adidas on 27 de fevereiro de 2017 - 7:22 am

  15. #15 by http://www.actulite.com/c-jewelry/c-bracelets on 27 de fevereiro de 2017 - 7:28 am

    I had gotten the as a gifts for my sister, pleased mom. She liked things!! I became nervous that had been going to be quite tiny due to the preceding recommendations and just how it looked when I took the optimum, however it healthy quite nicely. They styles perfect regarding plus the actual lovely package it is available inside.

  16. #16 by cheap christian louboutin on 27 de fevereiro de 2017 - 7:29 am

    I have your as being a gift to our sister, happy mom. She liked that it!! I was worried that was going to be quite limited due to the past evaluations and exactly how that it seemed once I got the top, however it fit quite nicely. This looks awesome on top of as well as in the actual lovely package it really is included inside.

  17. #17 by coach factory outlet online store on 27 de fevereiro de 2017 - 8:04 am

    Approaching from the standpoint of a fellow member within this trade, I really enjoy your write-up. I’ve constantly been in in actual fact like with this trade all my life so I’ve developed a discussion board for marketplace specialists to come together and discuss all things in this business. You gave me some fantastic creative concepts for my own website online.
    coach factory outlet online store http://www.lticonstruction.com/coach/

  18. #18 by bryant air conditioner price on 27 de fevereiro de 2017 - 8:28 am

  19. #19 by why not find out more on 27 de fevereiro de 2017 - 8:51 am

    This web site is my breathing in, really great pattern and perfect subject matter.

  20. #20 by tinder dating site on 27 de fevereiro de 2017 - 9:22 am

    Do you have a spam issue on this blog; I also am a blogger,
    and I was wanting to know your situation; we have created some nice methods and we are looking to trade techniques with others,
    be sure to shoot me an email if interested.

  21. #21 by http://www.word-vorlagen.net/ on 27 de fevereiro de 2017 - 9:29 am

    Hence when i requested it i thought information technology had been going to be letter awesome then again inexpensively manufactured bracelet ideal towards stocking stuffers. However it is prepared beautifully as well as is actually thick hence it really is not really synthetic or even quickly broken metal. My mother liked information technology. It is a little on the mini side when you posses a larger wrist i wouldnt encourage things however it is therefore worth that the discount amount!!

  22. #22 by http://www.hpmusik.se/hpmusik_cartier.asp on 27 de fevereiro de 2017 - 9:30 am

    This really is actually very. I love it plenty. Their quote are sweet furthermore container covered as part of wonderful bow. It isn’t the essential astonishing bracelet actually, but for the price that it exceeds my personal expectations. Can’twait to offer they and my mom concerning Mother’s evening!

  23. #23 by sergio rossi high heels on 27 de fevereiro de 2017 - 9:50 am

    Its crazy how much more attention I aquire from the other gender when I smoke cigars!
    sergio rossi high heels http://www.cheapsergiorossi.online

  24. #24 by http://freegoldgenerator.top/csgo-roulette-with-free-coins.html on 27 de fevereiro de 2017 - 10:43 am

    8  7Bezüglich „Made in Germany“ Natürlich ist sowas immer eine relative Betrachtung!Ich als ehemaliger Kraftfahrzeugführer (im Weitestens Sinne betrachtet, also als MKF eines Kampfpanzer Leopard II), kann über solche Qualitätsstandards natürlich nur lachen. Ein Fahrzeug das Problemlos einen Baum oder besagten VW-Golf niederwälzt, ohne davon einen Schaden zu bekommen. Hat mich die Präsentation trotzdem irgendwie überzeugt. Auch wenn man mit seinen geliebten Auto sowas nicht machen (Türen krachen und so ).

  25. #25 by corebyg on 27 de fevereiro de 2017 - 12:07 pm

    ■アリゾナ州クォーツサイト市には、5ヶ所の無料キャンプエリアがある。 米フロリダ(Florida)州オーランド(Orlando)のテーマパーク「ウォルト・ディズニー・ワールド・リゾート(Walt Disney World Resort)」のホテル前にある人工湖でワニに襲われ、行方不明になっていた男児(2)が、遺体で発見された。 [url=http://www.anstoss4-planet.de/Scprite/Forum/wbb216neu/thread.php?threadid=70307&sid=]win 8.1 インストール[/url]
    それもほとんどの受験生はPass4Testを選んだ理由です。 こりゃ、どう~も!今日もがんがって書いていきます。
    [url=http://mangable.com/forums/news-and-announcements/65777-.html]produkey office 2013[/url] こちらのサイトに解決法が書かれているので、もし「そういえば最近プチフリしだした」という方がいたら参考にしてください。 知らないうちに勝手にアップグレードされた方々も多いと聞いていたので、すぐに終わるかと思ったのですが、その日に終わりませんでした。
    [url=http://board.bananaking.co.uk/posting.php?mode=post&f=28]office2010 メディア 購入[/url]
    PassexamのJNCDA認定JN0-1100試験範囲を網羅した豊富な問題を解くことにより、本試験関する知識を含んで、自分の理解度を把握し、試験問題に慣れることができます。 http://itexammondaisyuu.seesaa.net/article/432627456.html弊社のMCSE: Communication資格70-336問題集はIT専門家によって作り上げられて、初心者としても認定に合格できます。 [url=http://www.anstoss4-planet.de/Scprite/Forum/wbb216neu/thread.php?threadid=70307&sid=]windows8 セットアップ[/url]
    嫁さんの希望は、宛名書きソフトのデータの引っ越し。 PhotoshopCs3の方には問題が出なかったので、サポートや認証は抜きで使い続けられそうです。
    [url=http://creationvsevolution.freeforums.org/office-t39834.html]produkey windows 10[/url] googleスプレッドシート最高や!excelでQRコードなんか、最初からいらんかったんや!。 OSの入れ替えはPCの心臓外科手術を行うようなもの。
    [url=http://mangable.com/forums/news-and-announcements/65777-.html]office 2013 価格[/url]

  26. #26 by outlet louis vuitton online on 27 de fevereiro de 2017 - 12:16 pm

    Personally Im impressed by the quality of this. Generally when I come across these sort of things I like to post them on Digg. This article probably wont do well with that crowd. Ill take a look around your site though and submit something else.
    outlet louis vuitton online

  27. #27 by clasificados.lavgps.com.mx on 27 de fevereiro de 2017 - 1:17 pm

    Lêiser remove a tonalidade junto afeição entretanto a tez admite
    queimaduras nesse autos, com finalidade de minorar a arrependimento se usa emanação perplexo, através também depois da determinação
    remissão laser todavia essas coisas não evita os efeitos colaterais das queimaduras
    nem planta a carcinoma de tez. http://clasificados.lavgps.com.mx/author/ionahotham/

  28. #28 by http://myfreecoins.top/star-stable-star-coin-generator.html on 27 de fevereiro de 2017 - 2:06 pm

    Didn’t know the forum rules allowed such brilliant posts.

  29. #29 by http://www.jaldety.com/default.asp on 27 de fevereiro de 2017 - 2:09 pm

    I have your as a gift to my sister, pleased mom. She adored things!! I was worried that is going to be quite slight due to the previous product reviews and exactly how they looked when I took one peak, but it match really nicely. This styles pretty in plus ones beautiful bundle it really is provided when.

  30. #30 by http://hackcheatstool.us/hit-it-rich-free-coins-loading-issue.html on 27 de fevereiro de 2017 - 3:25 pm

    I hope this is just a quick bump in the road, Shannon, and that Oliver resumes to his happy self very very soon. We've seen this quite a few times over the years with Sasha, exactly the same with car rides and stoller spins suddenly bringing her contentment when nothing else would. Please know we're thinking of you, and if I can recall any tips from those times I'll certainly let you know! Joanne

  31. #31 by coach outlets online on 27 de fevereiro de 2017 - 4:31 pm

    Blasphemy! LOL Just kidding. Ive read similar things on other blogs. Ill take your word for it. Stay solid! your pal.
    coach outlets online

  32. #32 by Hd Wallpapers For Desktop Free Download on 27 de fevereiro de 2017 - 4:32 pm

    “I recently came across your blog and have been reading along. I thought I would leave my first comment. I don�t know what to say except that I have enjoyed reading.”

  33. #33 by lk bennett handbags sale on 27 de fevereiro de 2017 - 6:17 pm

    There is obviously a lot to realize about this. I assume you made certain nice points in features also.
    lk bennett handbags sale

  34. #34 by http://myfreecoins.top/cheat-coins-plants-vs-zombies-android.html on 27 de fevereiro de 2017 - 6:18 pm

    Just wanted to say that I'm so glad you're blogging again :) While I loved following you on Twitter, it's so nice to see your posts show up in my Reader cue again! Love those boots… might be my 2013 purchase..

  35. #35 by please click the following post on 27 de fevereiro de 2017 - 6:41 pm

    Some truly interesting details you have written.Aided me a lot, just
    what I was searching for :D.

  36. #36 by iphone line free coins on 27 de fevereiro de 2017 - 6:55 pm

    Copiilor mei ( care au acum 21 si respectiv 22 de ani) nu le vine sa creada ce le povestesc eu. Lor li se pare inacceptabil si deloc REAL! ( desi au invatat si la istorie in clasele a opta si a XII-a). " Cum nu existau calculatoare, net, plasme, ciocolata, coca -cola, filme, parfumuri,etc. ?? Bine ca l-ati impuscat pe Ceausescu! " :(((

  37. #37 by edm parts on 27 de fevereiro de 2017 - 8:10 pm

    Here are several of the web-sites we advocate for our visitors

  38. #38 by http://www.kajson.se/laboutinreplica.aspx on 27 de fevereiro de 2017 - 8:17 pm

    I purchased our to the mother not anticipating a lot because information technology was so that inexpensive. When I collected they I became thrilled! It really is lovely & does not seem inexpensive after all! The mother liked it!

  39. #39 by http://www.cfcl.co.uk/ on 27 de fevereiro de 2017 - 8:18 pm

    I have this particular as a gifts concerning my sibling, satisfied mama. She loved they!! I was afraid information technology ended up being going to be as well mini because of the previous reviews and exactly how this looked once I took one peak, however it fit most well. Information technology looks striking on top of as well as in the lovely package it really is provided at.

  40. #40 by free coins on town of salem on 27 de fevereiro de 2017 - 8:27 pm

    I’m particularly prompted using your way with words-at all properly with all the format to the website. Is that this a compensated theme or perhaps do you adjust the item oneself? No matter what carry on outstanding quality producing, it’s uncommon to check out a fantastic web site like this one nowadays.

  41. #41 by http://hackcheatstool.us/zoosk-coin-generator-free-download.html on 27 de fevereiro de 2017 - 8:33 pm

    The truth just shines through your post

  42. #42 by louis vuitton outlet usa on 27 de fevereiro de 2017 - 8:40 pm

    Is not marriage an open question, when it is alleged, from the beginning of the world, that such who are in the institution wish to get out and such as are out wish to get in.
    louis vuitton outlet usa

  43. #43 by corelpr on 27 de fevereiro de 2017 - 9:00 pm

    (^-^;ただ今回購入したPCは用途を限らせて使用するため、高負荷処理は行う機会が非常に少ない事から割り切って使用する分には充分活躍してくれると思っています♪これからちょこちょこイジって行こうと思います。 Firefoxって名前は耳にしたことがあったのですが、もひとつうまく使いこなせないchromeみたいなものだろうと思ってあまり興味を引かれなかったんです。 [url=http://galactica.myforum.ro/viewtopic.php?p=842#842]office 2013 激安[/url]
    そして写真のようにLEDパネル同士をフラットケーブルで繋ぎ、電源ケーブルを繋ぎます。 いつまでも、いつまでもずっと落ちずに伸びて行く。
    [url=http://blog-gourmet.com/prbbs]office2016 の プロダクト キー[/url] 最終的に、Microsoftは完全な「Xbox Live」体験をWindows 10搭載PCにもたらすことを狙っている。 非Office365ユーザー向け価格は「Office2013」と同じで、139.99ドル(「Home& Student」エディション)からだ。
    [url=http://z12.invisionfree.com/JimmyCoatesForum/index.php?showtopic=14351]wi[/url]
    マイクロソフトからは、皆様のフィードバックに直接返信されないことにご注意ください。 データのデリートや初期化だけではデータを消去できていない。 [url=http://galactica.myforum.ro/viewtopic.php?p=846#846]office personal 2013 ダウンロード 版[/url]
    このことを理解しているのは、我が家では私一人です。 もっとも柳沢きみおが不得意とする読者層に対してのチャレンジだったのだろうか?巻末に2巻の予告がありますが・・・2巻は出ず未完で終了。
    [url=http://mixzing.freeforums.org/windows10-t92875.html]office2016 personal 価格[/url] ソフトバンクの音声サービスと日本マイクロソフトのクラウドPBXによる連携サービスの提供、モバイルセキュリティーの実現を目的とした24時間稼動のヘルプデスクの開設などを予定している。 先日海外ティザー予告編が公開された『美女と野獣』は、『スター・ウォーズ/フォースの覚醒』がトップを維持していたティザー予告編の初日再生回数記録を更新したことでも話題となった。
    [url=http://galactica.myforum.ro/viewtopic.php?p=846#846]office 2013 通販[/url]

  44. #44 by http://free-coins.club/does-paragon-give-free-coins-anymore.html on 27 de fevereiro de 2017 - 9:14 pm

    Apparently this is what the esteemed Willis was talkin’ ‘bout.

  45. #45 by http://leanforum.se/clreplica.asp on 27 de fevereiro de 2017 - 9:37 pm

    This is truly pretty. I like that a lot. Some sort of quote is actually adorable and also box wrapped in wonderful bow. It’s not the absolute most excellent bracelet actually, but for the price they exceeds our objectives. Can’twait on offer things on my personal mom of Mother’s evening!

  46. #46 by how does pokemon coin generator work on 27 de fevereiro de 2017 - 10:34 pm

    me neither, before the speech of Guido Bertelli I didn’t know almost anything about staminal cells and that’s a very interesting topic. Concerning sustainability and environment, thanks to [ comfort zone ] I have learnt what really means being sustainable and respecting OUR environment… very nice song!

  47. #47 by dedicated server hosting on 27 de fevereiro de 2017 - 11:29 pm

    very handful of internet websites that come about to become comprehensive beneath, from our point of view are undoubtedly nicely really worth checking out

  48. #48 by Moupjgb on 27 de fevereiro de 2017 - 11:32 pm

    彼はすでにそれを設立し、十億ドル以上の基金を,慈善のために寄付しています。 対弾道弾迎撃用にした場合宇宙空間にも到達可能かもしません。 [url=http://z12.invisionfree.com/JimmyCoatesForum/index.php?showtopic=14384]韓国ドラマ ママ~最後の贈りもの~ DVD-BOX[/url]
    確かに速いねんけど、色々と使いにくい点がある・・・。 やがてアメリカは、アフガニスタン空爆とイラク侵攻へと突き進むことになる。
    [url=http://blackhand.forumcity.com/viewtopic.php?p=3303#3303]韓国ドラマ 運命のように君を愛してる DVD-BOX激安[/url] そうか!日本は70%が山地なので、滝は多くあるわ。 何回も通い狙いを定めて、挑戦しないとダメだと思います。
    [url=http://www.regrbl.com/forum/viewtopic.php?f=3&t=239684]日本ドラマ 同窓生~人は、三度、恋をする~ DVD-BOX激安[/url]
    ホストウェブに AppUrl パラ メータを渡します。 ま、こうやって信頼していただけていることに感謝。 [url=http://mixzing.freeforums.org/topic-t95026.html]日本アニメ人気DVD box[/url]
    Microsoft Office 2007 suites (KB2687409) のセキュリティ更新プログラム。  クロームは比較的性能の低いハードウエアでも処理が高速です。
    [url=http://buzucan.myforum.ro/viewtopic.php?p=2001#2001]韓国ドラマ 奇皇后V -ふたつの愛 涙の誓い- DVD-BOX 価格[/url] これなどは「ユーザーの目をかいくぐって」Windows10にしてしまえという意図が見えます。 テキストフォルダーにまとめて、ソフト「ALZip」でPW付きZipファイルにすることで、1つのPWでその他全部を見られるようにしていました。
    [url=http://aceshardware.freeforums.org/topic-t74512.html]日本ドラマ ど根性ガエル DVD-BOX 価格[/url]

1 279 280 281
(não será publicado)